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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With