Sling Academy
Home/Node.js/Mongoose: $lt and $gt operators (with examples)

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

Last updated: December 30, 2023

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.

Next Article: Mongoose: 3 Ways to Remove All Documents from a Collection

Previous Article: Mongoose: Count Documents in a Collection (with examples)

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates