I'm searching for documents that contain a particular _id in the contacts array in the document. So here's the structure:
{
"_id": ObjectId("505c2daea9d397f2260001cd"),
"contacts": [
{
"userGroupId": ObjectId("50422b53743d6c7c0e000000"),
"userId": ObjectId("5061f8c66096eee07d000008")
},
{
"userGroupId": ObjectId("505bf9476096ee990200000e"),
"userId": ObjectId("505c2daea9d397f2260001ce")
},
{
"userGroupId": ObjectId("50422b75743d6c700e000004"),
"userId": ObjectId("506cff736096ee1e26000384")
},
{
"userGroupId": ObjectId("50422b66743d6c6b0e000000"),
"userId": ObjectId("505c2daea9d397f2260001cf")
},
{
"userGroupId": ObjectId("5050e86aa9d3977b67000000"),
"userId": ObjectId("506494ef6096ee021f000064")
},
{
"userGroupId": ObjectId("50422b53743d6c7c0e000000"),
"userId": ObjectId("504d72246096ee2348000008")
},
{
"userId": ObjectId("50735e8e6096ee7c510002b9"),
"userGroupId": ObjectId("5046c73e6096ee1b77000001")
}
]
}
Here's a second document:
{
"_id": ObjectId("505c2da0a9d397f2260000b7"),
"contacts": [
{
"userGroupId": ObjectId("50422b66743d6c6b0e000000"),
"userId": ObjectId("505c2da0a9d397f2260000b8")
},
{
"userId": ObjectId("5061f8c66096eee07d000008"),
"userGroupId": ObjectId("50422b53743d6c7c0e000000")
},
{
"userId": ObjectId("50735e8e6096ee7c510002b9"),
"userGroupId": ObjectId("5046c73e6096ee1b77000001")
}
]
}
You'll notice that both documents have a userId of ObjectId("50735e8e6096ee7c510002b9") in them. I run this command:
db.collection.find({ 'contacts':
{$elemMatch: { userId: ObjectId("50735e8e6096ee7c510002b9") } }
});
Which should (I think) return both documents. But it only returns the second document. Not the first. I have also tried:
db.collection.find({'contacts.userId': ObjectId("50735e8e6096ee7c510002b9") });
which does the same thing as the $elemMatch query.
I'm probably missing something really elementary, but if you guys could offer some advice I'd really appreciate it.
contactsis a numerically keyed object instead of an array is definitely the problem here. These queries shouldn't be returning anything (and didn't when I tried them on these docs).}in your$elemMatchquery, but other than that it's working as expected for me now, with both those queries returning both documents.