There are different comparison query operators provided by MongoDB and $in operator is one of them. Also, the $ in MongoDB operator is used to select the types of the document where the value of the field is equal to any given operator in the array. And also, if the field contains an array then this operator selects only those documents whose field contains an array. It holds one item that matches a value of the specified array. You can use $in operator in different methods like update(), find() according to your requirements. For more information you can read the documentation from here.

Also Read: Node js with MySQL: Everything you need to know


{field: {$in: [value1, value2, value3, ...]}}

In the example given below here is what we are working with.

Database: We found online
Collection: contributor
Document: three documents that contain the details of the contributors in the form of field-value pairs.

$ in MongoDB

Matching values using $in operator

Example given below we are retrieving only those employee’s documents whose names are either Amit or Suman.

db.contributor.find({name: {$in: ["Amit", "Suman"]}}).pretty()
$ in MongoDB

Matching values in an array using the $in operator

Now in this example we are trying to retrieve those employee’s documents who is working with either Python, C# or both the languages.

db.contributor.find({language: {$in: ["C#", "Python"]}}).pretty()
$ in MongoDB

Matching values in embeded/nested documents using $in operator

Now in this example we are getting the employee’s documents who got a specific number of marks in their semester.

db.contributor.find({"personal.semesterMarks":{$in: [80, 89, 78]}}).pretty()
$ in MongoDB

Updating data using the $in operator

Now in this example we will add a new field-value pair (i.e slalary: 10000) in the documents of Amit and Suman by using the update () method with $in and $set operators.

db.contributor.update({name: {$in: ["Amit", "Suman"]}}, {$set: {salary: 10000}})

Note: In this update () method you can only update one document at a time. Also, if you want to update multiple documents then set the value of its multi parameter to true. This example will show you how to use the update () mehtod updated the first document that matches the given condition that you can also see in the image given down below.


$ in MongoDB has quite different uses. Here is everything you need to know about the $ in MongoDB. We have explained each and every function of $in MongoDB with different examples. Here is everything you need to know. Thank you for reading this.

Categorized in:

Tagged in: