High performance find query using lean() in mongoose
Lets start with a basic find query in mongoose and observe its execution time.
[js]
Event.find({‘schedule.closing’: {‘$gte’: +new Date()}},
{},
{limit:20, skip:0}
).exec(function (err, events){
……..
……..
}
);
[/js]
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:
[js]
Event.find({‘schedule.closing’: {‘$gte’: +new Date()}},
{},
{limit:20, skip:0}
).lean().exec(function (err, events){
……..
……..
}
);
[/js]
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.
Hi,
Thanks for the good article .Can i use lean for mongoose findOneAndUpdate()?
Thumbs Up!
Short and good explanation, Sakshi Tyagi. Though not in detail, it still serves a purpose. Keep sharing the knowledge.
Very useful information for production applications where 1ms makes big differences. Thanks
Thank You Ajay!!
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 😉
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.
Thank you for the post…
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..
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.
Thanks Martin. Your reply has motivated me indeed. Sorry for late reply though.