Mongoose $match operator (with examples)

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

Introduction

This tutorial aims to provide an in-depth overview of the $match operator in Mongoose, which is an ODM (Object Data Modeling) library for MongoDB and Node.js. The $match operator is used primarily in aggregation to filter the documents of a collection similarly to the find operation. We will start with the basics before delving into more complex examples. Understanding this operator can significantly enhance your query-building skills in the context of a MongoDB database.

Getting Started

Before we move on to examples, let’s ensure you have Node.js installed. A basic understanding of MongoDB and how Mongoose interfaces with it is also assumed.
Install Mongoose with the following npm command:

npm install mongoose

Next, set up a base Mongoose connection to your MongoDB.

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase', {
 useNewUrlParser: true,
 useUnifiedTopology: true,
});

Let’s proceed by looking at a basic example of using the $match operator.

Basic Usage

The $match operator filters the document stream to allow only matching documents to pass unmodified into the next pipeline stage. For instance, if we wanted to find users in our database who are over 18 years old, our query would look something like this:

const User = mongoose.model('User', new mongoose.Schema({
 name: String,
 age: Number
}));

const findAdults = async () => {
 const adults = await User.aggregate([
 { $match: { age: { $gt: 18 } } }
 ]);

 console.log(adults);
};

findAdults();

This is equivalent to a User.find({ age: { $gt: 18 } }) but utilizing the aggregation framework.

Integrating $match with Other Stages

$match becomes more powerful when combined with other aggregation stages. For example, consider a scenario where we want to calculate the average age of all adult users.

const averageAdultAge = async () => {
 const avgAge = await User.aggregate([
 { $match: { age: { $gt: 18 } } },
 { $group: {
 _id: null,
 averageAge: { $avg: '$age' }
 } }
 ]);

 console.log(avgAge);
};

averageAdultAge();

We first filter out the adults and then group the results to calculate the average age using the $group operator.

Advanced Example

As we become more comfortable with $match, we can start to explore advanced queries that include complex filters and combinations with other aggregation operations.

What if we wanted to find all adult users with a criteria based on multiple fields? Here’s an example that demonstrates this:

const filterUsers = async () => {
 const filteredUsers = await User.aggregate([
 { $match: {
 $and: [
 { age: { $gt: 18 } },
 { name: /John/i }
 ]
 } },
 { $project: { name: 1, age: 1, _id: 0 } }
 ]);

 console.log(filteredUsers);
};

filterUsers();

In this query, we use the $and operator inside $match to combine the conditions.

We should also be aware that $match can take advantage of collection indexes when placed at the beginning of the aggregation pipeline, which optimizes query execution. For more complex datasets requiring faster operations, effective use of indexes becomes crucial.

Final Words

The $match operator in Mongoose is a versatile tool when working with MongoDB, allowing developers to filter and process data efficiently within the aggregation framework. Through the practical examples provided—from basic filtering to more advanced aggregation queries—it is clear that leveraging $match is key to performing powerful database operations. As you become comfortable with these examples, you’ll find that adding $match into your data manipulation arsenal will enhance the speed and abilities of your database queries dramatically.