I currently have a model set up in this way:
MyCollection
{
...
groups : [{ type: Schema.Types.ObjectId, ref: 'Group' }],
...
}
But I am facing an issue with finding all documents that contain a group with a specific _id. I attempted the following query:
MyCollection.find({
'groups' : {
$elemMatch : {
'$ref' : 'Group',
'$id' : myid
}
}
}).exec(cb);
However, this query is not yielding the desired results and has left me feeling frustrated.
Here is an example of a document:
{ _id: 52d7dd87f3f1e72c7c000005,
groups: [ { _id: 52d02565360c206933000013, name: 'groupname' } ],
date: Thu Jan 16 2014 10:15:00 GMT+0200 (EET),
...
}
Another attempt was made as follows:
> db.groups.find({ "name" : "NINFOS13"})
{ "_id" : ObjectId("52d8fad69c7817b52a000012"), "createdAt" : ISODate("2014-01- 17T09:41:42.365Z"), "name" : "NINFOS13", "__v" : 0 }
> db.subjects.insert({groups : [ { _id : ObjectId("52d8fad69c7817b52a000012"), name : "NINFOS13"}]})
> db.subjects.find()
{ "_id" : ObjectId("52d8fb7c1c4493a980630c68"), "groups" : [ { "_id" : ObjectId("52d8fad69c7817b52a000012"), "name" : "NINFOS13" } ] }
> db.subjects.find({"groups._id" : ObjectId("52d8fb7c1c4493a980630c68")}).count()
0
Upon further inspection, it appears that my previous query did work after all!