Reputation: 3596
I have the below 2 documents where I need to search if any of the documents have 4x4 or 3x3 within images array.
{
"images" : [
{
"4x4" : {
"path" : "4-1.jpg"
},
"2x2" : {
"path" : "2-1.jpg"
}
}
]
}
{
"images" : [
{
"3x3" : {
"path" : "3-1.jpg"
}
}
]
}
I have the below mongodb query. But cant seem to find way in using $or and $elemMatch together.
db.getCollection('images').find({
"images" : {
$elemMatch : {
"4x4" : {$exists : true}
}
}
})
Upvotes: 2
Views: 4581
Reputation: 50406
Well you can of course write it like this:
db.images.find({
"images": {
"$elemMatch": {
"$or": [
{ "4x4": { "$exists": true } },
{ "3x3": { "$exists": true } }
]
}
}
})
But you don't have to as you can basically write it like this:
db.images.find({
"$or": [
{ "images.4x4": { "$exists": true } },
{ "images.3x3": { "$exists": true } }
]
})
The $elemMatch
operator is generally only required when you need multiple conditions to match for an array "element". General array inspection or single property matches are better expressed with "dot notation".
Upvotes: 7