The mongoose $in Operator

Introduction

CRUD operations in mongoose are very important to understand. These operations include data retrieval, insertion, updating, and deletion. Mongoose provides several methods for such operations. All of these methods have a query and a projection part. A query specifies how the document will be filtered. Generally, it is an object. Have a look at the following object.

{"name" : "Rambo"}

If this is the query, resultant documents will be filtered according to their name fields. The output will contain only those documents where the value of the name field is “Rambo”. We can specify as many conditions in the query field. But in cases, where we need to filter according to only one field but more than on values. For example, if we want every document where the value of the name field is more than one value, then what? For such cases, mongoose provides the $in operator. In this article, we will discuss how to use $in operator.

We will use the $in method on the kennel collection.

{ "_id" : ObjectId("5dde131c7ece3115a2fbe600"), "name" : "Rambo", "age" : 5, "breed" : "Pitbull" }
{ "_id" : ObjectId("5dde135c7ece3115a2fbe601"), "name" : "Spike", "age" : 4, "breed" : "German Shephard" }
{ "_id" : ObjectId("5dde136e7ece3115a2fbe602"), "name" : "Maxi", "age" : 2, "breed" : "Pitbull" }
{ "_id" : ObjectId("5dde137b7ece3115a2fbe603"), "name" : "Tyke", "age" : 3, "breed" : "Great Dane" }
{ "_id" : ObjectId("5dde139b7ece3115a2fbe604"), "name" : "Leo", "age" : 2, "breed" : "German Shephard" }
{ "_id" : ObjectId("5dde13cb7ece3115a2fbe605"), "name" : "Romeo", "age" : 2, "breed" : "Doberman" }
{ "_id" : ObjectId("5dde13e97ece3115a2fbe606"), "name" : "Julie", "age" : 1, "breed" : "Pug" }
{ "_id" : ObjectId("5dde140c7ece3115a2fbe607"), "name" : "Scooby", "age" : 3, "breed" : "Great Dane" }

For performing HTTP endpoint testing, we will use the postman tool. You can download the postman tool from www.getpostman.com.

$in operator

The following route handler will be invoked when the endpoint ‘/getData’ will be executed.

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

It will return all the documents present in the kennel collection. There are different values of the breed field in the collection. Suppose we want only those documents where the value of the breed is either “Pitbull” or “Great Dane” or “Pug”. The simple and easy way is to use the $in operator.

The $in operator takes an array as its value. And $in operator, in turn, is assigned to the field according to which the filtration is to be done. Let’s use the $in operator.

{"breed" : { $in : ["Pitbull", "Great Dane", "Pug"]}}

We can see the $in operator is assigned to the breed field as an object. The value of the $in operator is an array that contains few values. The document will be matched where the value of the breed field matches any one of the values inside the array. Let’s add this to the route handler.

router.route('/getData').get(function(req,res){

    kennel.find({"breed" : { $in : ["Pitbull", "Great Dane", "Pug"]}}, function(err, result){

        if(err){
            res.send(err)
        }
        else{

            res.send(result)
        }

    })
})

Let’s execute this route using the postman tool.

Image from Gyazo

Yes! It returns only those documents where the value of the breed field is matched with at least one of the values specified in the array.

Conclusion

We hope you found this overview of the mongoose $in operator valuable. It’s very useful when you want to search for records where one of the properties is in a certain set of values. If you have any questions please don’t hesitate to call us at Object Rocket.

Just The Code

router.route("/getData").get(function(req, res) {
  kennel.find({ breed: { $in: ["Pitbull", "Great Dane", "Pug"] } }, function(
    err,
    result
  ) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

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.