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

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

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.