Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
APPLIES TO:
MongoDB vCore
The $in
operator filters documents where a field's value matches any value in a specified array, making it ideal for matching multiple criteria. It's especially useful for querying nested arrays and handling complex data structures efficiently.
{
field: { $in: [<value1>, <value2>, ...] }
}
Description | |
---|---|
field |
The field in the document you want to query. |
<value1>, <value2>, ... |
An array of values to match against the specified field. |
Let's understand the usage with sample json from stores
dataset.
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"name": "Lakeshore Retail",
"location": {
"lat": -9.9399,
"lon": -0.334
},
"staff": {
"totalStaff": {
"fullTime": 18,
"partTime": 7
}
},
"sales": {
"totalSales": 35911,
"salesByCategory": [
{
"categoryName": "DJ Headphones",
"totalSales": 35911
}
]
},
"promotionEvents": [
{
"discounts": [
{
"categoryName": "DJ Turntables",
"discountPercentage": 18
},
{
"categoryName": "DJ Mixers",
"discountPercentage": 15
}
]
},
{
"discounts": [
{
"categoryName": "DJ Accessories",
"discountPercentage": 18
},
{
"categoryName": "DJ Mixers",
"discountPercentage": 10
}
]
}
]
}
The example queries for document with specified _id
that have DJ Mixers
with a discount percentage of either 15
or 20
within the promotionEvents.discounts
array.
db.stores.find({ "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
,"promotionEvents.discounts.discountPercentage": { $in: [15, 20] }
},
{ "_id":1, "name":1, "promotionEvents.discounts":1}
)
The query returns document where the discounts
array contains any element with a discountPercentage
of either 15
or 20
, and only shows the complete discounts array for those documents
{
"id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"name": "Lakeshore Retail",
"promotionEvents": [
{
"discounts": [
{
"categoryName": "DJ Turntables",
"discountPercentage": 18
},
{
"categoryName": "DJ Mixers",
"discountPercentage": 15
}
]
}
]
}
- Review options for Migrating from MongoDB to Azure Cosmos DB for MongoDB (vCore)
- Read more about Feature compatibility with MongoDB