8

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?

johneth
  • 2,858
  • 5
  • 27
  • 26

2 Answers2

20

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"})
Kostanos
  • 9,615
  • 4
  • 51
  • 65
2

I'd recommend dumping the DBRefs in favor of simply storing the _id of the referenced document assuming you know the name of the collection being referenced.

There is absolutely no way to "resolve" an array of DBRef from 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 _id you can retrieve that array and then use the $in query to fetch them all.

So your document might change to look like this:

{
    "_id" : ObjectId("4e2d4892580fd602eb000003"),
    "date_added" : ISODate("2011-07-25T11:42:26.395Z"),
    "date_updated" : ISODate("2011-07-25T11:43:09.870Z"),
    ...
    "references": [
        ObjectId(123), ObjectId(234), ObjectId(567), ObjectId(891)
    ],
    ...
    "name" : "some name"
}

You can then query MongoDB using the contents of the references field:

db.somecollection.find({"_id": {"$in": references}})
Brendan W. McAdams
  • 9,379
  • 3
  • 41
  • 31
  • The reason I dislike this is because the use of DBRef means documents can be automatically serialized into their Java counterparts using MongoTemplate, for example. Otherwise serialization has to be customized – IcedDante Aug 03 '14 at 23:20
  • This is not useful answer. The question was 'how to find document with specific DBRef', not 'should I use DBRefs in my db'. Kostanos's answer is correct. – mc.watras Mar 22 '18 at 08:29