Suppose I have a collection like this:
{ "arr" : [ { "name" : "a", "num" : 1 }, { "name" : "a", "num" : 2 } ] },
{ "arr" : [ { "name" : "b", "num" : 1 }, { "name" : "a", "num" : 2 } ] },
{ "arr" : [ { "name" : "b", "num" : 1 }, { "name" : "b", "num" : 2 } ] }
and I want to find all documents who's arr contains a sub-document with a name = "b" and num = 2.
If I do a query like this:
db.collection.find({
$and: [
{ "arr.name": "b" },
{ "arr.num": 2 }
]
});
it will return all documents in the collection because they each contain a sub-document with either a name of "b" or a num of 2.
I've also tried this:
db.collection.find({
arr: [
{ "name": "b", "num": 2 }
]
});
which doesn't throw any errors, yet doesn't return any results.
How do you query on multiple sub-document fields in MongoDB?