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.
10 Answers
Since you don't need the count, you should make sure the query will return after it found the first match. Since count performance is not ideal, that is rather important. The following query should accomplish that:
db.Collection.find({ /* criteria */}).limit(1).size();
Note that find().count()
by default does not honor the limit
clause and might hence return unexpected results (and will try to find all matches). size()
or count(true)
will honor the limit flag.
If you want to go to extremes, you should make sure that your query uses covered indexes. Covered indexes only access the index, but they require that the field you query on is indexed. In general, that should do it because a count()
obviously does not return any fields. Still, covered indexes sometimes need rather verbose cursors:
db.values.find({"value" : 3553}, {"_id": 0, "value" : 1}).limit(1).explain();
{
// ...
"cursor" : "BtreeCursor value_1",
"indexOnly" : true, // covered!
}
Unfortunately, count()
does not offer explain()
, so whether it's worth it or not is hard to say. As usual, measurement is a better companion than theory, but theory can at least save you from the bigger problems.

- 45,391
- 6
- 76
- 82
-
3is `db.Collection.find({ /* criteria */}).limit(1).size();` synchronous? – moriesta Mar 21 '14 at 13:21
-
10You want `.count(with_limit_and_skip=True)`. There is no method called `.size()` – Arthur Tacca Nov 30 '16 at 14:48
-
3There doesn't seem to be a .size() method – Stephen Smith Jun 14 '18 at 18:08
I dont believe that there is a straight way of checking the existence of the item by its value. But you could do that by just retrieving only id (with field selection)
db.your_collection.find({..criteria..}, {"_id" : 1});
-
21
-
1Thanks. Since all IDs are indexed in the Memory, Will this query do anything with the disk? – Amin Shojaei Jul 19 '20 at 10:49
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 })

- 54,987
- 21
- 291
- 190
It is significantly faster to use find() + limit() because findOne() will always read + return the document if it exists. find() just returns a cursor (or not) and only reads the data if you iterate through the cursor.
db.collection.find({_id: "myId"}, {_id: 1}).limit(1)
(instead of db.collection.findOne({_id: "myId"}, {_id: 1})
).
Look at more details: Checking if a document exists – MongoDB slow findOne vs find

- 4,783
- 2
- 32
- 32
-
2`find()` will always return a cursor (even if the document does not exist - in that case `hasNext()` will return `false`. – Yuval A. Oct 26 '17 at 23:50
filter_dict = {"key":value}
if db.collection.count_documents(filter_dict):
print("item is existed")
else:
print("item is not existed")

- 41
- 1
-
3Although this code might solve the problem, a good answer should also explain **what** the code does and **how** it helps. – BDL Oct 13 '20 at 09:00
An update to Xavier's answer:
db.collection.countDocuments({}, { limit: 1 })
Expects a callback as a second argument now, so this can be used instead:
db.collection.countDocuments({}).limit(1)

- 329
- 2
- 12
I'm surprised to find the $exists
operator not being mentioned here.
db.collection.findOne({myFieldName: {$exists: 1}})
If you want the opposite (find one where the field does not exists):
db.collection.findOne({myFieldName: {$exists: 0}})
If you want to get a cursor, use find()
instad of findOne()
and you can get a boolean with db.collection.find({myFieldName: {$exists: 1}}).isExhausted()
Note that isExhausted()
is a mongo shell method only

- 526
- 4
- 10
-
because `$exist` is mint for other things than what's asked, Read the documentation carefully : `$exists matches the documents that contain the field, including documents where the field value is null. If
is false, the query returns only the documents that do not contain the field.` – Abdelghani Roussi Nov 16 '22 at 18:43 -
It will not perform a find, it just returns the documents that have a specific field/property – Abdelghani Roussi Nov 16 '22 at 18:44
Im currently using something like this:
async check(query) {
const projection = { _id: 1 };
return !!db.collection.findOne(query, projection);
}
It will return true or false, of course returning only _id: 1 for smallest data transfer.

- 74
- 6
I have simply used lodash framework - _isEmpty();
const {
MongoClient,
ObjectId
} = require('mongodb');
const _ = require('lodash');
MongoClient.connect(testURL, {
useNewUrlParser: true
}, (err, client) => {
let db = client.db('mycompany');
if (err) {
console.log('unable to connect to the mycompany database');
} else {
console.log('test connection to the database');
};
db.collection('employee').find({
name: 'Test User'
}).toArray((err, result) => {
if (err) {
console.log('The search errored');
} else if (_.isEmpty(result)) {
console.log('record not found')
} else {
console.log(result);
};
});
client.close();
});
If you use Java and Spring you can use that:
public interface UserRepository extends MongoRepository<User, ObjectId> {
boolean existsByUsername(String username);
}
It works for me.

- 19
- 5