I'm using NodeJs and native MongoDB driver for creating an application. I want to ensure that one record with a specific condition is exists or not and I want to know that which method is better?
collection.find({...}).count(function(err, count){
if(count > 0) {
//blah blah
}
})
or
collection.findOne({...}, function(err, object){
//blah blah
})
See this question. I believe find
with limit(1)
is way to go in your case. (If you want to get actual document data with query, then use findOne
).
In terms of mongodb-native
, code will look something like this
function recordExists(selector, callback) {
collection.find(selector, {limit: 1}, function(err, cursor) {
if (err) return callback(err);
cursor.count(function(err, cnt) {
return callback(err, !!cnt);
});
});
}
collection.find({...}).count
. Is native driver allows to do that? Is it cursor.count
? Anyway, limit
is your friend here.