简体   繁体   中英

How to select documents with specific elements in MongoDB with PHP?

I have the following structure of a mongo document:

{
 "_id": ObjectId("4fba2558a0787e53320027eb"),
 "replies": {
    "0": {
      "email": ObjectId("4fb89a181b3129fe2d000000"),
      "sentDate": "2012-05-21T11: 22: 01.418Z",
      "type": "one"
    } 
    "1": {
     "email": ObjectId("4fb89a181b3129fe2d000000"),
     "sentDate": "2012-05-21T11: 22: 01.418Z",
      "type": "two"
    } 
    "2" ....
 }

}

How do I select only documents containing only specific type of replies, for example "type":"one"? Thank you!

It simply worked like this, first time I was trying to do a group on it:

$cursor = $db->foo->find(
    array('replies.type' => 'one'), array('replies.sentDate')
);

Maybe it will help others like me. The keys "0", "1" ... have no effect.

Look to $elemMatch in mongo documentation I think it will help. http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24all

You may try this:

t.find({replies: {$elemMatch: { "type": "one" } } });

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