and in mongoose

Introduction

Every Mongoose method has a query part. The query consists of conditions according to which the documents will be matched. The query can be simple and it can be complicated as well. Observe the following query.

{ "breed" : "Labrador" }

The above query will match all the documents where the value of the breed field is “Labrador”. Now, observe the following kennel collection.

{ "_id" : ObjectId("5dfb436f3b2f7e06a2961d02"), "name" : "Rambo", "age" : 3, "breed" : "Labrador" }
{ "_id" : ObjectId("5dfb43773b2f7e06a2961d03"), "name" : "Scooby", "age" : 1, "breed" : "Labrador" }
{ "_id" : ObjectId("5dfb43843b2f7e06a2961d04"), "name" : "Rocky", "age" : 5, "breed" : "Pitbull" }
{ "_id" : ObjectId("5dfb43973b2f7e06a2961d05"), "name" : "Johnny Boy", "age" : 2, "breed" : "Great Dane" }
{ "_id" : ObjectId("5dfb43a33b2f7e06a2961d06"), "name" : "Snoopy", "age" : 4, "breed" : "Labrador" }

There are five documents and in three of them, the value of the breed field is “Labrador”. So we can use the query we defined earlier to fetch these three documents. Let’s make the query a bit complicated. Say, we want all the documents where the value of the age field is greater than 2. We can use the $gt operator for this.

{
  age: {
    $gt: 2;
  }
}

This will work fine. But the queries can get more complex in the real practice. Say, we want all the documents where the value of the age field is greater than 2, but less than or equal to 4, Then what? We can use the $gt operator and the $lte operator. But how? For such situations where we need to fulfill multiple conditions on a single field, we can use the $and operator. The $and operator only matches the documents when all the conditions specified in it are true. In this article, we will discuss how to use the $and operator in mongoose.

We will use the postman tool for testing. You can download it from www.getpostman.com.

$and operator

So we will fetch all the documents where the value of the age field is greater than 2 and less than or equal to 4. Let’s create a route handler first.

router.route("/fetchdata").get(function(req, res) {});

The above route handler will be invoked when the endpoint ‘/fetchdata’ is executed.

To fetch the documents, we can use the find() method. Let’s add it to the route handler.

router.route("/fetchdata").get(function(req, res) {
  kennel.find({}, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

Currently, we are passing an empty object as the query. It will fetch all the documents in the collection. For our requirements, we need to add the $and operator with proper conditions. Let’s do it. The $add operator takes an array of objects as its value. Each object will contain a condition.

{
  $and: [{ age: { $gt: 2 } }, { age: { $lte: 4 } }];
}

In the array, we need to provide each condition as an object. Let’s add it to the find() method and check what happens.

router.route("/fetchdata").get(function(req, res) {
  kennel.find({ $and: [{ age: { $gt: 2 } }, { age: { $lte: 4 } }] }, function(
    err,
    result
  ) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

Yes! It returns all the documents where the value of the age field is greater than 2 and less than or equal to 4.

Conclusion

We showed you how to combine conditions using the $and operator in mongoose. We used it inside of the find function and specified two conditions that we wanted met. You can of course specify more than two conditions and all of them will have to be met in order for the document to be returned. Most applications have a lot of custom logic and the $and operator is a great utility to apply some custom conditions that your application has. Thanks for joining us for another ObjectRocket knowledge base article.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.