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.
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();
});
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
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});