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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8303900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:49:26  来源:igfitidea点击:

mongodb/mongoose findMany - find all documents with IDs listed in array

mongodbnode.jsmongoose

提问by ezmilhouse

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

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

Something like ...

就像是 ...

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

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

The array might contain hundreds of _ids.

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

回答by Daniel Mendel

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

findmongoose 中的函数是对 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);
});

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

即使对于包含数万个 id 的数组,这种方法也能很好地工作。(请参阅有效确定记录的所有者

I would recommend that anybody working with mongoDBread through the Advanced Queriessection of the excellent Official mongoDB Docs

我建议任何工作的人mongoDB通读优秀的官方 mongoDB 文档高级查询部分

回答by SnnSnn

Ids is the array of object ids:

Ids 是对象 ID 的数组:

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

Using Mongoose with callback:

使用带有回调的猫鼬:

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

Using Mongoose with async function:

使用具有异步功能的猫鼬:

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

Don't forget to change Model with your actual model.

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

回答by Derese Getachew

Use this format of querying

使用这种查询格式

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();

回答by Nico

Both node.js and MongoChef force me to convert to ObjectId. This is what I use to grab a list of users from the DB and fetch a few properties. Mind the type conversion on line 8.

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 );
                }
            }
        });
    }