mongodb query on DBRef type

4,480 views
Skip to first unread message

willem dhaeseleer

unread,
Aug 2, 2015, 7:28:11 PM8/2/15
to mongodb-user

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 cars are "owned" by users consistently, of if cars can be owned by other collections as well. 

Stackoverflow question: 

Doug Reese

unread,
Aug 3, 2015, 9:57:53 PM8/3/15
to mongodb-user

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. 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.

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.

Doug
Reply all
Reply to author
Forward
0 new messages