mongodb 通过 id 集更新多个文档。猫鼬
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20096885/
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
Update multiple documents by id set. Mongoose
提问by user2960708
I wonder if mongoose has some method to update multiple documents by id set. For example:
我想知道猫鼬是否有一些方法可以通过 id 集更新多个文档。例如:
for (var i = 0, l = ids.length; i < l; i++) {
Element.update({'_id': ids[i]}, {'visibility': visibility} ,function(err, records){
if (err) {
return false;
} else {
return true;
};
});
};
What i want to know, that if mongoose can do something like this:
我想知道的是,如果猫鼬可以做这样的事情:
Element.update({'_id': ids}, {'visibility': visibility}, {multi: true} ,function(err, records){
if (err) {
return false;
}
});
where ids is an array of ids, like ['id1', 'id2', 'id3'] - sample array. Same question for find.
其中 ids 是一个 id 数组,例如 ['id1', 'id2', 'id3'] - 示例数组。寻找同样的问题。
回答by Salvador Dali
Most probably yes. And it is called using $inoperator in mongodb query for update.
很可能是的。它在 mongodb 查询中使用$in运算符调用以进行更新。
db.Element.update(
{ _id: { $in: ['id1', 'id2', 'id3'] } },
{ $set: { visibility : yourvisibility } },
{multi: true}
)
All you need is to find how to implement $in in mongoose.
您所需要的只是找到如何在 mongoose 中实现 $in 。
回答by Abhishek Singh
in updateManyfunction no need of { multi: true }
在updateMany函数中不需要 { multi: true }
db.collectionName.updateMany(
{
_id:
{
$in:
[
ObjectId("your object id"),
ObjectId("your object id")
]
}
},
{
$inc: { quantity: 100 }
})
I want to add one more point, you can use $into fetch multiple document
我想再补充一点,你可以使用$in来获取多个文档
db.collectionName.find(
{
_id:
{
$in:
[
ObjectId("your object id"),
ObjectId("your object id")
]
}
})