Consider we are searching a document from MongoDB based on the _id value. Which one of the following code is efficient ?
ModelObj.findById(IdValue).exec(callback);
ModelObj.findOne({ '_id': IdValue}).exec(callback);
I feel ModelObj.findById() is efficient, but what are the supportive reasons or How is it efficient?
findById is just a convenience function that does exactly the same thing as the findOne call you show.
Here's the source:
Model.findById = function findById (id, fields, options, callback) {
return this.findOne({ _id: id }, fields, options, callback);
};
Using .findOne makes the database look through its records checking each bson document to find the relevant variable and then check the value, if mongo knows its looking for the internally indexed _id field it doesn't have to look through each document
If mongoose is clever, then both calls should be equally fast, because it would automatically convert the findOne query to a findById query.
The reason why findById should be faster is, because the ID-field is usually indexed in the db. If a field is indexed, the database can lookup all matching entries by the value, instead of going through all entries and checking if the field-value is equal to the searched value. This is much faster.