Finding documents by array of DBRefs

johneth picture johneth · Jul 27, 2011 · Viewed 8k times · Source

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?

Answer

Kostanos picture Kostanos · Mar 30, 2013

Try this one, it worked for me:

db.<your collection>.find({"a_list_of_dbrefs.$id": ObjectID("4e2d48ab580fd602eb000004")})

You can also retrieve all elements which has the ref to collection:

db.<your collection>.find({"a_list_of_dbrefs.$ref": "somecollection"})