The solution is probably staring me in the face, but I haven’t had any luck in finding it. My problem is that I need to find all documents which contain specified DBRef. Here’s the structure of the collection to be searched:
{
"_id" : ObjectId("4e2d4892580fd602eb000003"),
"date_added" : ISODate("2011-07-25T11:42:26.395Z"),
"date_updated" : ISODate("2011-07-25T11:43:09.870Z"),
...
"a_list_of_dbrefs" : [
{
"$ref" : "somecollection"
"$id" : "4e2d48ab580fd602eb000004"
}
],
...
"name" : "some name"
}
I need to be able to retrieve a set of documents based on a DBRef appearing in a_list_of_dbrefs (some a_list_of_dbrefs may contain no DBRefs, others may contain 1, and others may contain more than 1).
How is this accomplished?
I’d recommend dumping the
DBRefs in favor of simply storing the_idof the referenced document assuming you know the name of the collection being referenced.There is absolutely no way to “resolve” an array of
DBReffrom the server-side (in a single step) on MongoDB and requires that you loop through the array on the client and individually resolve each document.Conversely, if you store an array of just the referenced
_idyou can retrieve that array and then use the$inquery to fetch them all.So your document might change to look like this:
You can then query MongoDB using the contents of the
referencesfield: