在 MongoDB 中查找包含字符串 ID 数组的文档

Find documents with array of string ID's in MongoDB

我有一个 ID 的字符串数组,我想将其与查找函数一起使用。

db.companies.find( { _id : { $in : arr} });

arr 看起来像这样,

[ '563a2c60b511b7ff2c61e938', '563a2c60b511b7ff2c61e8b7' ];

我从 documentation 看到 ObjectID() 不接受数组。如何使用此数组搜索文档列表?我是否必须重新创建数组以便所有元素都是 ObjectID?

一种选择是使用 map 函数从字符串 ID 列表中获取 ObjectId 的列表:

arr.map(function (id) {
  return ObjectId(id);
})

插入您的查询:

db.companies.find({_id: { $in: arr.map(function (id) {return ObjectId(id);})}})