Mongoose: $lt and $gt operators (with examples)

Updated: December 30, 2023 By: Guest Contributor Post a comment

Overview

Manipulating and querying data efficiently are key aspects of working with databases. In this article, we delve into using Mongoose’s $lt and $gt operators to query MongoDB documents with conditions on values less than or greater than the specified argument, accompanied by practical examples.

Prerequisites:

  • Basic understanding of Node.js and MongoDB
  • Familiarity with Mongoose ODM
  • Node.js and MongoDB installed on your system

Setting Up Your Mongoose Model

Before diving into the operators, you must declare a Mongoose model. Let’s set up a simple User model for our examples:

import mongoose from 'mongoose';

const userSchema = new mongoose.Schema({
  name: String,
  age: Number,
  createdAt: Date
});

const User = mongoose.model('User', userSchema);

Basic Querying with $lt and $gt

$lt (less than) and $gt (greater than) are direct and powerful querying tools in Mongoose:

// Find users younger than 30
User.find({ age: { $lt: 30 } })
   .then(users => console.log(users));

// Find users older than 20
User.find({ age: { $gt: 20 } })
   .then(users => console.log(users));

Combining $lt and $gt in a Range Query

To find documents within a range, combine both operators:

// Find users between 20 and 30
User.find({ age: { $gt: 20, $lt: 30 } })
   .then(users => console.log(users));

Using $lt and $gt with Dates

The operators also work seamlessly with date fields:

// Find users created after a specific date
const startDate = new Date('2023-01-01');
User.find({ createdAt: { $gt: startDate } })
   .exec()
   .then(users => console.log(users));

Async/Await Syntax

You can make your queries cleaner with async/await:

const findYoungUsers = async () => {
  const users = await User.find({ age: { $lt: 30 } });
  console.log(users);
};

findYoungUsers();

Advanced Queries with Aggregation

For more complex queries, turn to the aggregation framework:

// Average age of users older than 20
const pipeline = [
  { $match: { age: { $gt: 20 } } },
  { $group: { _id: null, avgAge: { $avg: '$age' } } }
];

User.aggregate(pipeline).then(result => console.log(result));

Error Handling

In production, always include error handling in your queries:

const findUsers = async () => {
  try {
    const users = await User.find({ age: { $gt: 20 } });
    console.log(users);
  } catch (error) {
    console.error('Query failed', error);
  }
};

findUsers();

Always sanitize and validate user inputs that might be used in your queries to prevent injection attacks.

Conclusion

Mongoose’s $lt and $gt operators are essential in constructing queries for ranges or specific conditions based on values. Through various examples, we’ve seen how they offer an efficient way to retrieve relevant documents and how you can integrate these queries into your applications using Mongoose and MongoDB.