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

就像……

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

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

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


当前回答

node.js和MongoChef都迫使我转换为ObjectId。这就是我用来从DB中获取用户列表并获取一些属性的方法。注意第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 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);
            }
        }
    });
}

其他回答

使用这种查询格式

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

node.js和MongoChef都迫使我转换为ObjectId。这就是我用来从DB中获取用户列表并获取一些属性的方法。注意第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 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);
            }
        }
    });
}

如果你正在使用async-await语法,你可以使用

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

我尝试如下,它为我工作。

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

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

不要忘记改变模型与您的实际模型。