MongoDB $in Operator: A Detailed Guide

Suppose you have a collection of students containing lots of documents having indexes like Name, Age, Class, etc. One of the indexes or attributes in the documents is Optional Subject. For context, an optional subject is a subject people choose beyond the regular curriculum subjects. 

So you want to filter students having Computer Science, Physical, and Singing as optional subjects. How would do do that? 

Here comes $in operator. We can make an array having Computer Science, Physical, and Singing as its elements then pass that array to $in the operator and specify the field as Optional Subject, and it searches all those documents where that field (Optional Subject) contains any of the one element (value in an array). The $in operator can be used with the find() operator to return those filtered documents.

In this article, we will be seeing a detailed guide on $in operator with some inside knowledge that will help you understand a practical approach to using it.

Also Read: Logical Query Operators in MongoDB

Comparison Query Operators

MongoDB has various comparison operators to match documents on the basis of some comparisons with specified values or expressions.

The following is the comparison operators table in MongoDB:

OperatorsDescription
$eqQuery documents that field values are equal to a specified value.
$gtQuery documents that field values are greater than a specified value.
$ltQuery documents that field values are less than a specified value.
$gteQuery documents that field values are greater than or equal to a specified value.
$lteQuery documents that field values are less than or equal to a specified value.
$inQuery documents that field values match any of the values in a specified array.
$ninQuery documents that field values do not match any of the values in a specified array.
$neQuery documents that field values are not equal to a specified value.


In the above table you have seen a short introduction to $in but let’s now deeply understand it, its syntax and an example demonstration.

MongoDB $in Operator

The $in operator is used to select documents inside a collection by comparing the values of a field with any of the values in the array. 

Note: If the value of the field of documents is an array, the $in operator will select only those documents whose field holds an array that contains at least one element that matches a value in the specified array

Syntax:

{ field: { $in: [<value1>, <value2>, ... <valueN> ] }

Parameter:

Here, the field is which value you want to match with at least one value inside the given array. 

Important: 

The operator in MongoDB including $in cannot used individually to filter documents, it can only be combined with find, update, delete, etc. functions to do its job.

Coming back to the topic, if you find the above syntax confusing, let’s see a quick example of this operator.

Examples of Using $in Operator in MongoDB 

Suppose, you have a website for selling drones and for storing data you are using MongoDB. Let’s see examples to filter documents on the basis of an array using the $in operator. We will also then update some documents using $in operator.

Follow the steps below to demonstrate the example with us:

  • Start your MongoDB server
  • Pass this command to list all your databases and use your preferred one:
show dbs
use droneStore
  • Now, list out all the documents in a collection of a chosen database. We can then use the $in operator on them to filter out based on specific values.
db.drones.find({})

{ "_id" : ObjectId("6034fd2bf74cfd0438bdb19b"), "utility" : [ "Photography" ], "onSale" : false, "name" : "SV - Aira 157B", "price" : 2455, "weight" : "467 grams", "__v" : 0 }

{ "_id" : ObjectId("603502ba24df1c2350e676e7"), "utility" : [ "Monitoring or Inspection", "Security" ], "onSale" : false, "name" : "SV - Terrus D40", "price" : 5259, "weight" : "764 grams", "__v" : 0 }

{ "_id" : ObjectId("603502ba24df1c2350e676e8"), "utility" : [ "Recreation" ], "onSale" : false, "name" : "SV - Jovio J259", "price" : 1500, "weight" : "247 grams", "__v" : 0 }

{ "_id" : ObjectId("603502ba24df1c2350e676e9"), "utility" : [ "Delivery" ], "onSale" : false, "name" : "SV - CARRIER X288", "price" : 105499, "weight" : "26 kilograms", "__v" : 0 }

{ "_id" : ObjectId("60352beadecee830681c3b62"), "utility" : [ "Delivery" ], "onSale" : false, "name" : "SV - Grander 345X8", "price" : 43535, "weight" : "23 kilograms", "__v" : 0 }

{ "_id" : ObjectId("60352ecb6ce2811cc8892a75"), "utility" : [ "Monitoring or Inspection" ], "onSale" : false, "name" : "SV - LaserX AW205", "price" : 4000, "weight" : "2.3 kilograms", "__v" : 0 }

{ "_id" : ObjectId("6157239d341d653bccaf7822"), "utility" : [ "Recreation" ], "onSale" : false, "name" : "DF - Jetfire Nitro RX-V", "price" : 22000, "weight" : "3 kilograms", "__v" : 0 }

{ "_id" : ObjectId("6157240c341d653bccaf7823"), "utility" : [ "Monitoring or Inspection" ], "onSale" : false, "name" : "Pink Sentinel Q95", "price" : 13000, "weight" : "2 kilograms", "__v" : 0 }

{ "_id" : ObjectId("61573885341d653bccaf7825"), "utility" : [ "Security" ], "onSale" : false, "name" : "SV - Xorvia 9908Y", "price" : 7760, "weight" : "3.8 kilograms", "__v" : 0 }

{ "_id" : ObjectId("615738d6341d653bccaf7826"), "utility" : [ "Photography" ], "onSale" : false, "name" : "SV - Ryee SW657", "price" : 8900, "weight" : "760 grams", "__v" : 0 }

{ "_id" : ObjectId("61573946341d653bccaf7827"), "utility" : [ "Monitoring or Inspection" ], "onSale" : false, "name" : "RV - Zereca Eagle-i", "price" : 3200, "weight" : "1.7 kilograms", "__v" : 0 }

{ "_id" : ObjectId("615739bb341d653bccaf7828"), "utility" : [ "Delivery" ], "onSale" : false, "name" : "OS - Falcon GO!", "price" : 45000, "weight" : "17 kilograms", "__v" : 0 }

Finding Documents Using $in Operator Matching Array Values

Let us now use the $in operator to look for drones having “Recreation” and “Security” as their utility.

> db.drones.find({utility: {$in: ["Security", "Recreation"]}})

{ "_id" : ObjectId("603502ba24df1c2350e676e7"), "utility" : [ "Monitoring or Inspection", "Security" ], "onSale" : false, "name" : "SV - Terrus D40", "price" : 5259, "weight" : "764 grams", "__v" : 0 }

{ "_id" : ObjectId("603502ba24df1c2350e676e8"), "utility" : [ "Recreation" ], "onSale" : false, "name" : "SV - Jovio J259", "price" : 1500, "weight" : "247 grams", "__v" : 0 }

{ "_id" : ObjectId("6157239d341d653bccaf7822"), "utility" : [ "Recreation" ], "onSale" : false, "name" : "DF - Jetfire Nitro RX-V", "price" : 22000, "weight" : "3 kilograms", "__v" : 0 }

{ "_id" : ObjectId("61573885341d653bccaf7825"), "utility" : [ "Security" ], "onSale" : false, "name" : "SV - Xorvia 9908Y", "price" : 7760, "weight" : "3.8 kilograms", "__v" : 0 }

As you can notice, we have four documents filtered-out documents where the value of the utility field is “Recreation”, “Security” or both.

Updating Documents Using $in Operator Matching Array Values

Let us now use the $in operator to update documents matching array values.

Among the results we got from the above example, there is a drone having “SV – Jovio J259” as its name:

{ "_id" : ObjectId("603502ba24df1c2350e676e8"), "utility" : [ "Recreation" ], "onSale" : false, "name" : "SV - Jovio J259", "price" : 1500, "weight" : "247 grams", "__v" : 0 }

Let’s try to change the price field of this drone from 1500 to 200 using $in operator.

> db.drones.update({name: {$in: ["SV - Jovio J259"]}}, {$set: {price: 2000}})

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let’s understand the above code. Here we have first used the $in operator to create a condition so that we can get those drones where the name field is “SV – Jovio J259”, which is of course only one. Then we used the $set operator to change the price field of that select drone to 2000. 

If you want to learn more about the $set operator, click here.

Let us now check the document again using the $in operator although we could simply use the find() method here.

> db.drones.find({name: {$in: ["SV - Jovio J259"]}})

{ "_id" : ObjectId("603502ba24df1c2350e676e8"), "utility" : [ "Recreation" ], "onSale" : false, "name" : "SV - Jovio J259", "price" : 2000, "weight" : "247 grams", "__v" : 0 }

See the document is successfully updated.

Conclusion

In this tutorial, we have learned about different types of operators, specifically the $in operator to select documents that match the element of a given array. We have not only learned to find but also update documents by using the $in operator. That’s the end of this guide, hope you got solutions to all your doubts!

Continue Reading:

Reference

MongoDB Manual on $in operator

Aneesha S
Aneesha S
Articles: 171