Reputation: 423
It's possible to write a query that always returns all of the elements in a collection, to use pymongo as an example:
MongoClient()["database"]["collection"].find({})
However, due to the structure of my code, I would quite like to be able to construct a query that does the opposite, a query that will necessarily return zero elements in all situations:
MongoClient()["database"]["collection"].find(null_query)
How can I define null_query
, such that this is correct?
Upvotes: 3
Views: 1376
Reputation: 9891
You can ask for any field to be in an empty list. It seems reasonable to use the _id
field for this:
db.collection.find({_id: {$in: []}})
If you want a shorter query you don't need to use the _id
field
at all:
db.collection.find({_:{$in:[]}})
Arguably one can also ask if the _id
field does not exists, which has been suggested by @Marco13:
db.collection.find({_id: {$exists: false}})
However, this assumes that all documents have the _id
field, which is not necessarily true for MongoDB versions before 3.4 where a collection could be created with db.createCollection("mycol", {autoIndexID : false})
so all documents were not automatically given an _id
field.
Upvotes: 2