Introduction to MongoDB $in Operator
MongoDB is a document database widely used in web applications and large-scale data processing scenarios. The $in
operator is a query operator in MongoDB that matches multiple values during a query.
Syntax
The MongoDB $in
operator uses the following syntax:
{ field: { $in: [<value1>, <value2>, ...] } }
Here, field
is the field to be matched, $in
represents matching multiple values, and <value1>, <value2>, ...
is a list of values to be matched.
Use Cases
The $in
operator is suitable for scenarios where multiple values need to be matched. Common applications include:
- Querying multiple values: When you need to find multiple specific values in a field, you can use the
$in
operator. For example, to query all products in a collection that cost 20, 30, or 40:
db.products.find({ price: { $in: [20, 30, 40] } })
- Excluding multiple values in a query: Use the
$nin
operator to exclude multiple values. For example, to query all products in a collection whose prices are not 20, 30, or 40:
db.products.find({ price: { $nin: [20, 30, 40] } })
- Using a subquery in a query: The
$in
operator can be used in a subquery. For example, to query all orders in a collection that contain a specific product:
db.orders.find({
product_id: { $in: db.products.find({ name: "iPhone" }, { _id: 1 }) }
})
Examples
Suppose there is a collection named students
containing the following documents:
{ "_id" : ObjectId("6145a5a5dd3d3e84b48a058a"), "name" : "Alice", "age" : 25, "grade" : 85 }
{ "_id" : ObjectId("6145a5b5dd3d3e84b48a058b"), "name" : "Bob", "age" : 23, "grade" : 90 }
{ "_id" : ObjectId("6145a5c2dd3d3e84b48a058c"), "name" : "Charlie", "age" : 22, "grade" : 75 }
{ "_id" : ObjectId("6145a5d1dd3d3e84b48a058d"), "name" : "David", "age" : 26, "grade" : 80 }
{ "_id" : ObjectId("6145a5dddd3d3e84b48a058e"), "name" : "Emma", "age" : 24, "grade" : 95 }
Now, we want to query students who are 25 or 26 years old. We can use the $in
operator to achieve this:
db.students.find({ age: { $in: [25, 26] } })
After running the above command, the following documents will be returned:
{ "_id" : ObjectId("6145a5a5dd3d3e84b48a058a"), "name" : "Alice", "age" : 25, "grade" : 85 }
{ "_id" : ObjectId("6145a5d1dd3d3e84b48a058d"), "name" : "David", "age" : 26, "grade" : 80 }
Conclusion
The $in
operator is a commonly used query operator in MongoDB that allows matching multiple values in a query. It can be used in various scenarios, such as querying for multiple values, excluding multiple values in a query, and using subqueries in a query.