简体   繁体   中英

Find all documents in mongodb

I want to display all documents (select *) with sub-documents in PHP.

I know how to query all find() but I have no idea how to do it when I have sub-documents. I don't know if there's something like find() or I need to make loops fo every sub-documents that I'd have.

This would be the code

$mongodatabase->insertOne(
    ['name' => 'Alex',
    'surname' => 'Turner',
    'country' => 'England',
    'birth' => array(
        'day' => 6,
        'month' => 'january',
        'year' => 1986
    ),
]);

Something easy, just to learn. When I try a var_dump of day I get Undefined index and NULL.

$client = new MongoDB\client;
$db = $client->database;
$mongodatabase = $db->document;
$document = $mongodatabase->find();

foreach ($document as $doc) {
     var_dump($doc->day);
}

However, I'd like to query all.

Use $exists - It helps us in identifying the elements which are not empty

db.collection_name.find({
   "birth.day" : { 
      $exists : true
   }
});

If you need to check not null and empty, then we need to use $type together with $exists , $type can be passed with different values and 10 is for null check

db.collection_name.find({
   "birth.day" : { 
      $not : { $type : 10 },
      $exists : true
   }
});

when u find the exactly data from mongoldb u can use the shelter to limit the field eg:

db.xxxxx.find(
    {'status':'DELIVRD'}
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM