High performance find query using lean() in mongoose

13 / Feb / 2015 by Sakshi Tyagi 9 comments

Lets start with a basic find query in mongoose and observe its execution time.

 Event.find({'schedule.closing': {'$gte': +new Date()}},
        {},
        {limit:20, skip:0}
    ).exec(function (err, events){
 ........
 ........
  }
);

In my last project on Nodejs, I have used the above query to fetch the events from “Event” collection satisfying the given condition. After computing the average execution time, it came out to be 218ms.

Then, I applied lean() in the same query:

 Event.find({'schedule.closing': {'$gte': +new Date()}},
        {},
        {limit:20, skip:0}
    ).lean().exec(function (err, events){
 ........
 ........
  }
);

This time the average execution time came out to be 71ms which is drastically less than the without “lean” version of the same query.

So, you must be wondering what exactly lean() did here?

As described by the mongoose docs, documents returned from queries with the lean option true are plain javascript objects, not Mongoose Documents. They have no save method, getters/setters or other Mongoose magic applied. So in this way the over head attached to the mongoose document is not there in case of lean and we get high performance.

FOUND THIS USEFUL? SHARE IT

comments (9)

  1. Yogesh Jadhav

    Short and good explanation, Sakshi Tyagi. Though not in detail, it still serves a purpose. Keep sharing the knowledge.

    Reply
  2. lewis

    this is really useful stuff. keep on going. dont listen to people who think otherwise. people need this kind of knowledge. i am using mongoose now and i will be exploring this. thanks and cheers ;)

    Reply
  3. Sakshi Tyagi

    Hi Garima, thank you for your feedback on the blog. The intend behind this blog was just to share a useful mongoose property which might prove helpful to some people . There is no bounds set to what we can call a blog, the basic idea is knowledge sharing. Please let me know what additional details you were expecting from this blog , so that I can make it better.

    Reply
  4. Garima

    I was a proud subscriber of intelligrape’s Blogs, but now after seen this blog it seems that you are posting blog on a property. While you know that we readers don’t need this, we need application of concept., details explanation instead of just to tell lean..

    Reply
    1. Martin

      Garima, who made you the supreme being to decide what we need? This post was actually super helpful for me, as I have some performance issues to deal with in a large production app.

      Reply

Leave a comment -