How to query mongodb with DBRef How to query mongodb with DBRef mongodb mongodb

How to query mongodb with DBRef


Got it:

db.post.find({'author.$id': 'foo'})


This db.post.find('author.$id': 'foo') has missing the {}, so the correct sentence is:

db.post.find({'author.$id': 'foo'})

Also this can be achieved with:

db.post.find({'author': DBRef("user", ObjectId('foo'))})

But is more compact and practical the first way.


You can use the .$id reference but it will ignore any indexes on those fields. I would suggest ignoring that method unless you are querying it directly via the terminal or want to look up something quickly. In using large collections you will want to index the field and query it using the below method.

If you want to use an index query using the following:

db.post.find('author' : { "$ref" : 'user', "$id" : 'foo' , "$db" :'database_name' })

If foo is an object id

db.post.find('author' : { "$ref" : 'user', "$id" : ObjectId('foo') , "$db" :'database_name' })

You can create an index on author by

db.post.ensureIndex( {'author' : 1 } );