39

Consider we are searching a document from MongoDB based on the _id value. Which one of the following code is efficient ?

  1. ModelObj.findById(IdValue).exec(callback);

  2. ModelObj.findOne({ '_id': IdValue}).exec(callback);

I feel ModelObj.findById() is efficient, but what are the supportive reasons or How is it efficient?

Amol M Kulkarni
  • 21,143
  • 34
  • 120
  • 164

4 Answers4

57

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);
};
Dimitri
  • 2,023
  • 18
  • 23
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
28

findById(id) is almost equivalent to findOne({ _id: id }).
If you want to query by a document's _id, use findById() instead of findOne().

Both functions trigger findOne(), the only difference is how they treat undefined.
If you use findOne(), you'll see that findOne(undefined) and findOne({ _id: undefined }) are equivalent to findOne({}) and return arbitrary documents.
However, mongoose translates findById(undefined) into findOne({ _id: null }).

See https://mongoosejs.com/docs/api.html#model_Model.findById

Here's the source:

Model.findById = function findById(id, projection, options, callback) {
  if (typeof id === 'undefined') {
    id = null;
  }

  if (callback) {
    callback = this.$wrapCallback(callback);
  }

  return this.findOne({_id: id}, projection, options, callback);
};
Ronen Teva
  • 1,345
  • 1
  • 23
  • 43
1

findById(id) is just syntactic sugar of the find({_id : id}) or findOne({_id: id})

Prem
  • 5,685
  • 15
  • 52
  • 95
-3

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

Jye Lewis
  • 678
  • 3
  • 16