Search for documents by DBRefs array

The solution probably looks in my face, but I was not lucky enough to find it. My problem is that I need to find all documents containing the specified DBRef. Here is the structure of the collection to search for:

{ "_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 get a set of DBRef-based documents appearing in a_list_of_dbrefs (some a_list_of_dbrefs may not contain DBRefs, others may contain 1, and others may contain more than 1).

How is this achieved?

+7
source share
2 answers

I would recommend dropping the DBRef in favor of simply storing the _id referenced document, provided that you know the name of the referenced link.

There is absolutely no way to "resolve" the DBRef array from the server side (in one step) to MongoDB and requires that you skip the array on the client and individually allow each document.

Conversely, if you only store an array of reference _id , you can get that array and then use the $in query to retrieve all of them.

So your document might 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}}) 
+2
source

Try this, it worked for me:

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

You can also get all the elements that have a link to the collection:

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

All Articles