How to Use $in Operator in MongoDB Queries
In MongoDB, use the
$in operator to find documents where a field's value matches any value in a specified array. It works like saying "give me all documents where this field is one of these values." You include it inside a query object with the field name and an array of values.Syntax
The $in operator is used inside a query to match documents where the field's value is in a list of specified values.
- field: The name of the field to check.
- $in: An array of values to match against the field.
json
{ field: { $in: [value1, value2, value3, ...] } }Example
This example shows how to find all documents in a collection where the category field is either "fruit" or "vegetable".
mongodb
db.products.find({ category: { $in: ["fruit", "vegetable"] } })Output
[
{ "_id": 1, "name": "Apple", "category": "fruit" },
{ "_id": 3, "name": "Carrot", "category": "vegetable" }
]
Common Pitfalls
Common mistakes when using $in include:
- Using a single value instead of an array, which causes the query to fail or return no results.
- Confusing
$inwith equality;$inexpects an array of values. - Using
$inon fields that contain arrays without understanding how MongoDB matches array elements.
mongodb
/* Wrong: single value instead of array */ db.products.find({ category: { $in: "fruit" } }) /* Right: array of values */ db.products.find({ category: { $in: ["fruit"] } })
Quick Reference
| Operator | Description | Example |
|---|---|---|
| $in | Matches any value in the specified array | { field: { $in: [1, 2, 3] } } |
| $nin | Matches values not in the specified array | { field: { $nin: [1, 2, 3] } } |
Key Takeaways
Use $in with an array of values to match any of those values in a field.
$in helps find documents where a field equals one of many possible values.
Always provide an array to $in, not a single value.
Understand how $in works with array fields to avoid unexpected results.