MongoDB 数组查询 $in 操作

$in 操作:
查询 field 值与指定数组中任何值相等的 MongoDB 文档.

对于不同的 BSON 类型值,可参考 specified BSON comparison order

{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }

如果 field 是一个数组,则 $in 操作是,查询 field 数组中至少包含一个元素,可以与指定数组 <value1>, <value2> 有一个值相匹配.

1. 示例

1.1. $in 操作之匹配值Match Values

如:

db.inventory.find( { qty: { $in: [ 5, 15 ] } } )

该查询操作返回 inventory 集合中,qty 值是 5 或 15 的所有文档.

虽然该查询操作也可以采用 $or 操作,但,当进行相等性查询时,选择 $in 操作.

1.2. $in 操作之匹配数组中元素值 Match Values in an Array

如,inventory 集合包含 tags field:

{ _id: 1, item: "abc", qty: 10, tags: [ "school", "clothing" ], sale: false }

则,以下 update() 操作,针对 tags field 中的数组中至少有一个元素值等于 appliancesschool 的文档,会设置其 sale field 值由 false 设为 true.

db.inventory.update(
                     { tags: { $in: ["appliances", "school"] } },
                     { $set: { sale:true } }
                   )

更多查询数组的示例,参考:

1.3. $in 操作之正则表达式

$in 操作也可以采用正则表达式来匹配值,形式如 /pattern/.
如:

db.inventory.find( { tags: { $in: [ /^be/, /^st/ ] } } )

该查询操作返回 incentory 集合中 tags filed 中的元素至少包含 best 开头中所有文档.

[1] - 正则表达式 $regex

[2] - MongoDB - 正则式查询 $regex

Last modification:November 8th, 2018 at 10:44 am