MongoDB is a fantastic NoSQL database that’s flexible, fast, and scalable making it a go-to choice for many developers. But even the best databases can use a little tuning now and then. So, whether you’re looking to squeeze out a little more speed, reduce memory usage, or avoid those dreaded slow queries, this guide is for you! Here are ten quick and easy ways to optimize MongoDB, Node.js, and your server performance. Buckle up, because your database is about to get much faster.
Prerequisites
- Basic knowledge of JavaScript
- Basic knowledge of MongoDB
- Basic knowledge of Mongoose
Lets break down the task into smaller steps.
- Index Your Queries
- Limit and Skip, But Not Too Much
- Projections
- Use Aggregation
- Lean Queries
- Bonus: Use exist() instead of findOne()
1. Index Your Queries 🔍
Indexes are among MongoDB's most essential tools. Without them, MongoDB would have to scan every document in a collection, which can quickly turn a search into a slog.
MongoDB Shell
db.users.createIndex({ username: 1 });
Mongoose (Node.js)
UserSchema.index({ username: 1 })
2. Limit and Skip, But Not Too Much ⏲
Limit and skip are two handy functions in MongoDB that can help you paginate your results. But be careful! If you use them too much, you can slow down your queries.
MongoDB Shell
db.users.find().limit(10).skip(10);
Mongoose (Node.js)
User.find().limit(10).skip(10)
3. Projections 🔦
Bro what is this?
Projection is a way to select only the fields you need from a document. This can help reduce the amount of data you need to transfer and speed up your queries as you’re only fetching the data you need.
MongoDB Shell
db.users.find({}, { username: 1, email: 1 });
Mongoose (Node.js)
User.find({}, { username: 1, email: 1 })
User.find().select('username email')
User.find().select({ username: 1, email: 1 })
4. Use Aggregation 🧮
Wait, Dont run away. Aggregation is a powerful tool in MongoDB that can help you transform and manipulate your data. It can also help you speed up your queries by reducing the amount of data you need to transfer.
I know the times when you were scared of aggregation, and used to fetch raw data and then manipulate it in your code. But now, it's time to use aggregation. If you find it hard or scray, you can always ask me for help.
MongoDB Shell
db.users.aggregate([
{ $match: { age: { $gt: 18 } } },
{ $group: { _id: '$country', count: { $sum: 1 } } }
]);
Mongoose (Node.js)
User.aggregate([
{ $match: { age: { $gt: 18 } } },
{ $group: { _id: '$country', count: { $sum: 1 } } },
])
5. Lean Queries 🏃♂️
This one I guess only applies to Mongoose. When you use lean queries, aka lean()
, Mongoose will return plain JavaScript objects instead of Mongoose documents. This can help speed up your queries as you’re not dealing with the overhead of Mongoose documents.
So whats the catch? You can't use Mongoose methods on lean queries. But if you’re just fetching data, lean queries can be a great way to speed up your queries.
Here is difference between lean and non-lean queries.
// Non-lean query
const user
= await User.findOne({ username: 'sohail' });
// Time: 10ms, Memory: 10kb
// Lean query
const user
= await User.findOne({ username: 'sohail' }).lean();
// Time: 5ms, Memory: 5kb
Bonus: Use exist() instead of findOne() 🎉
If you just want to check if a document exists, use exists()
instead of findOne()
. This can help speed up your queries as you’re not fetching the entire document.
const userExists
= await User.exists({ username: 'sohail' });
Why exist() is faster than findOne()? Because exists()
only checks if the document exists,
and returns _id
if it does, while findOne()
fetches the entire document which could be of 1kb or 1mb.
Conclusion
That's it. I hope you found these tips helpful. If you have any questions or need help like this article and I will be posting more MongoDB, Next.js, Node.js and GraphQl related articles. If you havn't already, you can follow me on here on dev.to.
Top comments (1)
As a beginner with database i struggle alot but with all this tips and tricks it feels so easy, thank you for making such content and teaching us that you have learned over years
Wishing you many more blog for future 💪🧿