ChatGPT解决这个技术问题 Extra ChatGPT

mongodb/mongoose findMany - 查找 ID 列在数组中的所有文档

我有一个 _ids 数组,我想相应地获取所有文档,最好的方法是什么?

就像是 ...

// doesn't work ... of course ...

model.find({
    '_id' : [
        '4ed3ede8844f0f351100000c',
        '4ed3f117a844e0471100000d', 
        '4ed3f18132f50c491100000e'
    ]
}, function(err, docs){
    console.log(docs);
});

该数组可能包含数百个 _id。


C
Community

mongoose 中的 find 函数是对 mongoDB 的完整查询。这意味着您可以使用方便的 mongoDB $in 子句,其工作方式与 SQL 版本相同。

model.find({
    '_id': { $in: [
        mongoose.Types.ObjectId('4ed3ede8844f0f351100000c'),
        mongoose.Types.ObjectId('4ed3f117a844e0471100000d'), 
        mongoose.Types.ObjectId('4ed3f18132f50c491100000e')
    ]}
}, function(err, docs){
     console.log(docs);
});

即使对于包含数万个 id 的数组,这种方法也能很好地工作。 (见Efficiently determine the owner of a record

我建议任何使用 mongoDB 的人通读优秀的 Official mongoDB DocsAdvanced Queries 部分


这个讨论有点晚了,但是您如何确保返回的项目的顺序与您在数组中提供的项目数组的顺序相匹配?除非您指定排序,否则不保证文档以任何顺序出现。如果您希望它们按照您在数组中列出的顺序(例如...000c、...000d、...000e)进行排序怎么办?
由于某种原因,这不起作用。我有一个空的文档数组
@chovy 首先尝试 converting them to ObjectIds,而不是传递字符串。
@Kevin 您可能对此答案感兴趣:stackoverflow.com/a/22800784/133408
@Schybo 这完全没有区别。 { _id : 5 }{ '_id' : 5 } 相同。
s
snnsnn

Ids 是对象 ID 的数组:

const ids =  [
    '4ed3ede8844f0f351100000c',
    '4ed3f117a844e0471100000d', 
    '4ed3f18132f50c491100000e',
];

使用 Mongoose 和回调:

Model.find().where('_id').in(ids).exec((err, records) => {});

使用带有异步功能的 Mongoose:

const records = await Model.find().where('_id').in(ids).exec();

或者更简洁:

const records = await Model.find({ '_id': { $in: ids } });

不要忘记用您的实际模型更改模型。


这应该是公认的答案,因为它是最新且连贯的答案。您不必像接受的答案那样将 id 转换为 ObjectId,它使用猫鼬命令式查询。谢谢顺便说一句!
这是一个非常干净和更新的方法,如果你不介意我想问几个问题,如果我有一个像上面那样引用的 ObjectId 数组(比如说,我有项目,我分配了具有在用户模型上引用的 project_id 的特定用户的项目数组),如果我删除一个项目,我如何确保从用户模型引用的数组中删除 id ?谢谢垫子。
这就是我需要的!它干净且易于使用在另一个模型中作为参考的 id
这很好用!对于优化版本,您可以在末尾附加 .lean() ,它将仅返回 POJO(普通旧 Javascript 对象)。您还可以添加 select() 并仅选择文档的必填字段。
A
Ahmad Agbaryah

结合丹尼尔和 snnsnn 的答案:

让 ids = ['id1','id2','id3'] 让数据 = await MyModel.find( {'_id': { $in: ids}} );

简单而干净的代码。它适用于并经过测试:

“mongodb”:“^3.6.0”,“猫鼬”:“^5.10.0”,


我一直将 id 放在数组括号 [] 内,但从您的回答中意识到它已经是一个数组:|
@RizaKhan 非常感谢你!我犯了同样的错误。
l
long.luc

使用这种查询格式

let arr = _categories.map(ele => new mongoose.Types.ObjectId(ele.id));

Item.find({ vendorId: mongoose.Types.ObjectId(_vendorId) , status:'Active'})
  .where('category')
  .in(arr)
  .exec();

f
fafa.mnzm

从 mongoDB v4.2 和 mongoose 5.9.9 开始,这段代码对我来说很好用:

const Ids = ['id1','id2','id3']
const results = await Model.find({ _id: Ids})

并且 Id 可以是 ObjectIdString 类型


完美运行。
N
Nico

node.js 和 MongoChef 都强制我转换为 ObjectId。这就是我用来从数据库中获取用户列表并获取一些属性的方法。注意第 8 行的类型转换。

// this will complement the list with userName and userPhotoUrl based on userId field in each item
augmentUserInfo = function(list, callback){
        var userIds = [];
        var users = [];         // shortcut to find them faster afterwards
        for (l in list) {       // first build the search array
            var o = list[l];
            if (o.userId) {
                userIds.push( new mongoose.Types.ObjectId( o.userId ) );           // for the Mongo query
                users[o.userId] = o;                                // to find the user quickly afterwards
            }
        }
        db.collection("users").find( {_id: {$in: userIds}} ).each(function(err, user) {
            if (err) callback( err, list);
            else {
                if (user && user._id) {
                    users[user._id].userName = user.fName;
                    users[user._id].userPhotoUrl = user.userPhotoUrl;
                } else {                        // end of list
                    callback( null, list );
                }
            }
        });
    }

userIds = _.map(list, function(userId){ return mongoose.Types.ObjectId(userId) };
我不必使用 mongoose 4.5.9 转换为 ObjectID。
M
MD SHAYON

如果您使用的是 async-await 语法,您可以使用

const allPerformanceIds = ["id1", "id2", "id3"];
const findPerformances = await Performance.find({ _id: { $in: allPerformanceIds } });
           

U
Uma Devi Hariram

我在下面尝试过,它对我有用。

var array_ids=['1','2','6','9'] // your array of ids
model.find({ '_id': { $in: array_ids }}).toArray(function(err, data) {
            if (err) {
                logger.winston.error(err);
            } else {
                console.log("data", data);
            }
        });

T
Tiny Bot

我正在使用此查询来查找 mongo GridFs 中的文件。我想通过它的 ID 来获得。

对我来说,此解决方案有效:Ids type of ObjectId

gfs.files
.find({ _id: mongoose.Types.ObjectId('618d1c8176b8df2f99f23ccb') })
.toArray((err, files) => {
  if (!files || files.length === 0) {
    return res.json('no file exist');
  }
  return res.json(files);
  next();
});

这不起作用:Id type of string

gfs.files
.find({ _id: '618d1c8176b8df2f99f23ccb' })
.toArray((err, files) => {
  if (!files || files.length === 0) {
    return res.json('no file exist');
  }
  return res.json(files);
  next();
});