mongodb query on DBRef type

Willem D'Haeseleer picture Willem D'Haeseleer · Jul 31, 2015 · Viewed 7.6k times · Source

How do I turn this query in a valid mongodb Query in mongodb shell.

{ 'cars.owner.$ref' : 'users' } 

cars.owner is a DBRef here, but $ref is invalid

I get this error:

"$err" : "Positional operator does not match the query specifier."

My objective here is to figure out if there are any cars "owned" by different collections then users.

Answer

dreese picture dreese · Aug 3, 2015

You can query the DBRef in the Mongo shell, but you have to use the DBRef() function. The reference must include at least the $ref and $id. From the docs:

DBRef documents resemble the following document:

{ "$ref" : <value>, "$id" : <value>, "$db" : <value> }

When cars.owner is a reference to a document in the users collection, a query to find all cars where owner is a certain _id might look like (assuming both collections are in the same database):

db.cars.find({ "owner" : DBRef("users", ObjectId("<user _id value>")) })

The $ref and $id values cannot be queried directly. The DBRef is most useful in the case where there are multiple references to different collections in the same document. Using DBRef might be overkill when there is only one reference in the document, as others have mentioned.

If you need to reference different collections in your owners field, you are probably better served by using separate owner_collection and owner_id fields. The query to find all owners that are not users would then be a standard query:

db.cars.find({ owner_collection: { $ne: "users" } })