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

时间:2011-11-28 23:31:12

标签: mongodb node.js mongoose

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

像...一样的东西。

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

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

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

7 个答案:

答案 0 :(得分:404)

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的人阅读优秀Advanced Queries

Official mongoDB Docs部分

答案 1 :(得分:8)

使用这种查询格式

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

答案 2 :(得分:6)

结合Daniel和snnsnn的答案:

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

简单干净的代码。它的工作原理和测试条件是:

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

答案 3 :(得分:5)

Ids是对象ID的数组:

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

将Mongoose与回调一起使用:

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

将Mongoose与异步功能配合使用:

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

别忘了用实际模型更改模型。

答案 4 :(得分:4)

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

答案 5 :(得分:0)

从mongoDB v4.2和mongoose 5.9.9开始,此代码对我来说效果很好:

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

,并且ID的类型可以为ObjectIdString

答案 6 :(得分:0)

我尝试过如下所示,它对我有用。

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);
            }
        });
相关问题