Does MongoDB offer a find or query method to test if an item exists based on any field value? We just want check existence, not return the full contents of the item.
Starting Mongo 2.6, count has a limit optional parameter, which makes it a viable alternative to find whether a document exists or not:
db.collection.count({}, { limit: 1 })
// returns 1 if exists and 0 otherwise
or with a filtering query:
db.collection.count({/* criteria */}, { limit: 1 })
Limiting the number of matching occurrences makes the collection scan stop whenever a match is found instead of going through the whole collection.
Starting Mongo 4.0.3, since count() is considered deprecated we can use countDocuments instead:
db.collection.countDocuments({}, { limit: 1 })
or with a filtering query:
db.collection.countDocuments({/* criteria */}, { limit: 1 })