$in(数组表达式)
适用对象: MongoDB vCore
$in
运算符筛选字段的值与指定数组中的任何值匹配的文档,因此非常适合匹配多个条件。 它对于查询嵌套数组和高效处理复杂数据结构特别有用。
{
field: { $in: [<value1>, <value2>, ...] }
}
说明 | |
---|---|
field |
要查询的文档中的字段。 |
<value1>, <value2>, ... |
要与指定字段匹配的值数组。 |
让我们了解 stores
数据集中的示例 json 的用法。
{
"_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
}
]
}
]
}
示例查询具有指定 _id
的文档,该文档在 promotionEvents.discounts
数组中具有 DJ Mixers
,折扣百分比为 15
或 20
。
db.stores.find({ "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
,"promotionEvents.discounts.discountPercentage": { $in: [15, 20] }
},
{ "_id":1, "name":1, "promotionEvents.discounts":1}
)
查询返回文档,其中 discounts
数组包含任何 discountPercentage
为 15
或 20
的元素,并且仅显示这些文档的完整折扣数组
{
"id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"name": "Lakeshore Retail",
"promotionEvents": [
{
"discounts": [
{
"categoryName": "DJ Turntables",
"discountPercentage": 18
},
{
"categoryName": "DJ Mixers",
"discountPercentage": 15
}
]
}
]
}