Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding documents by array of DBRefs

Tags:

mongodb

dbref

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?

like image 760
johneth Avatar asked Jul 27 '11 15:07

johneth


2 Answers

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"})
like image 100
Kostanos Avatar answered Sep 25 '22 16:09

Kostanos


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}})
like image 34
Brendan W. McAdams Avatar answered Sep 23 '22 16:09

Brendan W. McAdams