Sling Academy
Home/Node.js/Mongoose: Compare Mumbers in a Query (Basic & Advanced)

Mongoose: Compare Mumbers in a Query (Basic & Advanced)

Last updated: December 30, 2023

When dealing with numeric data in MongoDB using Mongoose, it’s common to need filtering based on numerical conditions like greater than or less than. This tutorial will guide you through the syntax and provide examples of how to create queries with these comparisons in Mongoose.

Getting Started

Before diving into numerical comparisons, ensure you have a Mongoose model set up. For our examples, we’ll consider a ‘Product’ model with a ‘price’ field. The model is defined as follows:

import mongoose from 'mongoose';

const productSchema = new mongoose.Schema({
  name: String,
  price: Number
});

const Product = mongoose.model('Product', productSchema);

Basic Queries

Greater Than

To filter products with prices greater than a specific value use the ‘>’ operator:

const expensiveProducts = await Product.find({ price: { $gt: 100 } });

Less Than

For products cheaper than a certain price, use the ‘<‘ operator:

const cheapProducts = await Product.find({ price: { $lt: 50 } });

Combination of Greater and Less Than

To find products within a price range, combine ‘>’ and ‘<‘:

const midRangeProducts = await Product.find({ price: { $gt: 50, $lt: 100 } });

Additional Comparisons

Inequality

To query products excluding a specific price:

const notSpecificPriceProducts = await Product.find({ price: { $ne: 75 } });

Greater Than or Equal To

For filtering products with prices greater than or equal to a value:

const productsOrMore = await Product.find({ price: { $gte: 100 } });

Less Than or Equal To

To find those with prices less than or equal to a specific value:

const productsOrLess = await Product.find({ price: { $lte: 50 } });

Using Aggregation for Advanced Queries

The aggregation framework provides powerful ways to manipulate and analyze data. Find products with an average price greater than a specific value:

const avgPriceResult = await Product.aggregate([
  {
    $group: {
      _id: null,
      avgPrice: { $avg: '$price' }
    }
  },
  {
    $match: {
      avgPrice: { $gt: 75 }
    }
  }
]);

Querying with Indexes for Efficiency

To optimize performance, particularly on large datasets, ensure the ‘price’ field is indexed:

productSchema.index({ price: 1 });

// You'd typically call this line at application startup
mongoose.connect('your-mongodb-uri', { useNewUrlParser: true });

Conclusion

In conclusion, Mongoose provides a straightforward and powerful syntax for querying numeric data using conditions. By endowing queries with logical conditions such as greater than, less than, and ranges, you can effectively retrieve and manipulate data in a MongoDB database. Leverage these queries to make your application more dynamic and responsive to user needs.

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

Previous Article: Mongoose: Compare two dates in a query (before, after, between)

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