MongoDB/Mongoose Findmany-查找所有文档,其中包含数组中列出的ID
题
我有一系列_ids,我想相应地获取所有文档,最好的方法是什么?
就像是 ...
// doesn't work ... of course ...
model.find({
'_id' : [
'4ed3ede8844f0f351100000c',
'4ed3f117a844e0471100000d',
'4ed3f18132f50c491100000e'
]
}, function(err, docs){
console.log(docs);
});
阵列可能包含数百个_ids。
解决方案
这 find
Mongoose中的功能是对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的阵列,此方法也可以很好地工作。 (看 有效地确定记录的所有者)
我建议任何与之合作的人 mongoDB
通读 高级查询 优秀的部分 MongoDB官方文档
其他提示
使用这种查询格式
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 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 );
}
}
});
}
IDS是对象ID的数组:
const ids = [
'4ed3ede8844f0f351100000c',
'4ed3f117a844e0471100000d',
'4ed3f18132f50c491100000e',
];
使用猫鼬与回调:
Model.find().where('_id').in(ids).exec((err, records) => {});
使用异步函数使用Mongoose:
records = await Model.find().where('_id').in(ids).exec();
不要忘记使用您的实际模型更改模型。
不隶属于 StackOverflow