mongodb/mongoose findMany-查找所有ID在数组中列出的文档 [英] mongodb/mongoose findMany - find all documents with IDs listed in array

查看:84
本文介绍了mongodb/mongoose findMany-查找所有ID在数组中列出的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an array of _ids and I want to get all docs accordingly, what's the best way to do it ?

类似...

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

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

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

The array might contain hundreds of _ids.

推荐答案

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

The find function in mongoose is a full query to mongoDB. This means you can use the handy mongoDB $in clause, which works just like the SQL version of the same.

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

即使对于包含成千上万个id的数组,此方法也将很好地工作. (请参阅有效地确定记录的所有者)

This method will work well even for arrays containing tens of thousands of ids. (See Efficiently determine the owner of a record)

我建议与mongoDB合作的任何人通读 官方mongoDB文档

I would recommend that anybody working with mongoDB read through the Advanced Queries section of the excellent Official mongoDB Docs

这篇关于mongodb/mongoose findMany-查找所有ID在数组中列出的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆