![]() |
VOOZH | about |
MongoDB $in operator provides a powerful way to query documents based on multiple potential values for a specific field within a single query.
In this article, We will learn about the MongoDB $in Operator by understanding various examples in detail.
$in operator is used to match documents where the value of a field equals any value in a specified array. The $in operator allows you to match documents where a field's value is within a specified array. If you're building full-stack applications that need advanced querying capabilities, the Full Stack Development with Node JS course teaches you how to use operators like $in to filter data effectively
Syntax:
{field: {$in: [value1, value2, value3, ...]}}The query `{field: {$in: [value1, value2, value3, ...]}}` in MongoDB matches documents where the field `field` has a value that is contained within the specified array `[value1, value2, value3, ...]`.
It efficiently retrieves documents that match any of the values listed, offering a concise way to filter data based on multiple possible criteria in a single query.
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.
Output:
👁 Image$in Operator to Match Values 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()Output:
👁 Image$in Operator to Match Values in an ArrayIn 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()Output:
👁 Image$in Operator to Match Values in an Embedded ArrayIn 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()Output:
👁 Image$in Operator to Update DataIn 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}})Output:
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.
The MongoDB $in operator is a versatile tool for querying and updating documents based on multiple values efficiently. It simplifies the process of filtering documents that match any of the specified criteria within a single database operation.