Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb: find documents where at least one array element matches?

I have a document with the following structure:

[{
    "items": [
        {
            "sent_to_lab": 123,
            "received_from_lab": 456,
        },
        {
            "sent_to_lab": 123,
        },
    ]
}
... more orders ...
]

I want to fetch all orders where at least one item matches the following criteria:

'$and': [
    {'items.sent_to_lab': {'$exists': True}},
    {'items.received_from_lab': {'$exists': False}},
]

So in this case, I would like to return the aforementioned item, because at least one element of the items array matches my criteria.

How can I do this in mongo?

like image 575
poundifdef Avatar asked Mar 02 '13 00:03

poundifdef


1 Answers

You need to use the $elemMatch operator:

db.collection.find({items:
                     {$elemMatch:{
                           sent_to_lab:{$exists:true},
                           received_from_lab:{$exists:false}}
})

This is query $elemMatch - if you only want to get back the item that matched the condition (and not the entire document with the whole array) then you can use the projection $elemMatch operator similarly.

like image 140
Asya Kamsky Avatar answered Sep 21 '22 16:09

Asya Kamsky