DEV Community

Cover image for 5 Quick And Easy MongoDB Optimizations (part 1)
Sohail Jafri
Sohail Jafri

Posted on • Updated on

5 Quick And Easy MongoDB Optimizations (part 1)

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.

  1. Index Your Queries
  2. Limit and Skip, But Not Too Much
  3. Projections
  4. Use Aggregation
  5. Lean Queries
  6. 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 });
Enter fullscreen mode Exit fullscreen mode

Mongoose (Node.js)

UserSchema.index({ username: 1 })
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Mongoose (Node.js)

User.find().limit(10).skip(10)
Enter fullscreen mode Exit fullscreen mode

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 });
Enter fullscreen mode Exit fullscreen mode

Mongoose (Node.js)

User.find({}, { username: 1, email: 1 })
User.find().select('username email')
User.find().select({ username: 1, email: 1 })
Enter fullscreen mode Exit fullscreen mode

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 I were scared of aggregation, and used to fetch raw data and then manipulate it in 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 } } }
]);
Enter fullscreen mode Exit fullscreen mode

Mongoose (Node.js)

User.aggregate([
  { $match: { age: { $gt: 18 } } },
  { $group: { _id: '$country', count: { $sum: 1 } } },
])
Enter fullscreen mode Exit fullscreen mode

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 such as update() or save() 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
Enter fullscreen mode Exit fullscreen mode

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' });
Enter fullscreen mode Exit fullscreen mode

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 reach me out via socials 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.

Get In Touch

Co-Authors

Top comments (5)

Collapse
 
sahilchaubey profile image
sahilchaubey03

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 💪🧿

Collapse
 
devops_devrel profile image
Memories From

Great Article

Collapse
 
sahil_chaubey_45db49be580 profile image
WebDevReigns

Helped me a lot thank you so much

Collapse
 
sahil_chaubey_5417dfa7caa profile image
ReactNinja

Can't wait for part 2

Collapse
 
sahil_reigns_4776e181e6f7 profile image
Sahil Reigns

Super helpful article