mongodb / mongoose findMany – 查找列表中列出的所有文件

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

就像是 …

// doesn't work ... of course ... model.find({ '_id' : [ '4ed3ede8844f0f351100000c', '4ed3f117a844e0471100000d', '4ed3f18132f50c491100000e' ] }, function(err, docs){ console.log(docs); }); 

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

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的数组,这种方法也能正常工作。 (请参阅有效确定logging的所有者 )

我build议任何使用mongoDB阅读优秀官方mongoDB文档的Advanced Queries部分

node.js和MongoChef都强制我转换为ObjectId。 这是我用来从DB获取用户列表并获取一些属性。 注意第8行的types转换。

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

使用这种查询格式

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