MongoDB $in Operator

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.