Skip to content
Related Articles

Related Articles

Improve Article

MongoDB $in Operator

  • Last Updated : 22 Apr, 2020

MongoDB provides different types of comparison query operators and $in operator is one of them. This operator is used to select those documents where the value of the field is equal to any of the given value in the array. And if the field contains an array, then this operator selects only those documents whose field contains an array that holds at least one item that matches a value of the specified array. You can use this operator in methods like find(), update(), etc. according to your requirements.

Syntax:

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

In the following examples, we are working with:

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



Matching values using $in operator:

In this example, we are retrieving only those employee’s documents whose name is either Amit or Suman.




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

Matching values in an array using $in operator:

In this example, we are retrieving only those employee’s documents who is working with either C#, Python, or both languages.




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

Matching values in embedded/nested documents using $in operator:

In this example, we are retrieving only those employee’s documents who got the given marks in their semester.




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

Updating data using $in operator:

In this example, we are adding a new field-value pair(i.e, salary: 10000) in the documents of Amit and Suman by using update() method with $in and $set operators.




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

Note: The update() method by default update only one document at a time. If you want to update multiple documents, then set the value of its multi parameter to true. So, in this example, the update() method updated the first document that matches the given condition as shown in the below image.




My Personal Notes arrow_drop_up
Recommended Articles
Page :