0

I'm dynamically constructing and modifying a query in code.

I want a certain codepath to have the Collection return 0 documents.

I simply do Collection.find({_id:null}) . This seems to work.

Just wondering if there was a more standard way to do this in MongoDB. Thanks!

1 Answer 1

2

null is a valid value for _id, so while that query may be fine for your data, in general it's not guaranteed to produce the empty result set:

MongoDB Enterprise > db.foo.insert({_id:null})
WriteResult({ "nInserted" : 1 })
MongoDB Enterprise > db.foo.find()
{ "_id" : null }
MongoDB Enterprise > db.foo.find({_id:null})
{ "_id" : null }
MongoDB Enterprise > 

_id however does need to be present in each document, therefore a query insisting it isn't present should always return the empty result set:

db.foo.find({_id:{$exists:false}})

This only works for queries on top-level documents, naturally.

Sign up to request clarification or add additional context in comments.

1 Comment

null is fine for my data because there's validation on _id. But your solution is airtight. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.