在 MongoDB 中的指定数组中搜索
Shihab Sikder
2022年7月18日
MongoDB
MongoDB In
$in 运算符在你提供的数组中搜索。例如,如果你给出一个数组并希望在 MongoDB 集合中搜索一个或多个匹配的元素,那么你可以使用 $in。
使用 $in 运算符在 MongoDB 中搜索指定的数组
$in 运算符查找字段值等于所提供数组中的任何值的文档。使用以下原型来指定 $in 表达式。
{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }
例如,假设你有以下集合。
{
_id:1,
name: "John",
age: 30
},
{
_id:2,
name: "Alex",
age: 23
},
{
_id:3,
name: "Murphy",
age: 25
},
{
_id:4,
name: "Alice",
age: 28
},
现在,你想查看 _id = 2,3,4 的文档。因此,命令将如下所示。
db.collection.find( {_id: { $in: [2, 3, 4] } } );
或者,你也可以发送一个数组作为参数。当你开发应用程序或网站时,它会很有用。
let list=[2, 3, 4]
db.collection.find( { _id:{ $in: list} } )
在使用 JavaScript promises 时,这种方法很有用。
为避免错误,你应该注意 ObjectId。_id 默认由 MongoDB 提供,_id 的类型是 ObjectId。
因此,在将数组传入 $in 的参数时,最好将每个整数 id 转换为 ObjectId,如下所示。
{ "_id" : { $in : [ObjectId('2'),ObjectId('3'),ObjectId('4')] } }
这种方法更准确,因为你通过参数提供了 _id 的确切数据类型。 $in 也可用于 updateMany、updateOne、deleteOne、deleteMany 操作。
要了解有关 $in 运算符的更多信息,请访问此处的官方页面。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Shihab Sikder
