node.js - Update collection with $in clause mongodb
问题描述
I have a mongo collection I need to update (around 120k documents) and I have an array of values I want to take as a filter to match documents to update. For every document, I need to add the same property with the same value.
Is that possible to use the $in clause in mongodb in an update query to achieve that ?
Right now, I'm just looping through my array of values and updating my documents one at a time and it doesn't feel right.
let ps = ["user1", "user2"]; // my array
for(let i = 0; i < ps.length; i++){
// my function that updates on document and adds a property to it.
await Partname.update_partname(ps[i], "has_image", true);
}
That is basically what I want to achieve :
db.getCollection('partnames').update({
user: {
$in: ["user1", "user2"]
}
}, "has_image", true)
Thanks for your help.
解决方案
这里有两件事,
1.如果您有集合的模式,那么
确保您更新架构以具有"has_image"
正确类型的字段,然后触发您的查询。
使用这个查询:
db.collection("logs").update({"users": {$in: ["user1", "user2"]}},
{$set:{"has_image": true}},
{multi: true},
(err, data) =>{
//todo
})
这里的关键是使用multi: true
更新查询选项,让您一次更新多个文档。
此外,您必须$set
在更新查询中使用。
2.如果您没有任何收集模式,那么
你是自由的,只需触发上述查询。
建议:
如果您要在 $in 运算符中使用的数组中的值是用户的id(即集合中的 ObjectId),那么请确保先将它们转换为 ObjectId。
推荐阅读
- sql - 如何在 Presto 中将数组拆分为多列
- windows - Windows 服务的 CSV 比较
- java - List vs LinkedList vs ArrayList
- elasticsearch - 如何进行嵌套术语查询
- javascript - 缩小粘性粘性标题会导致 Blink/Webkit 在某些滚动位置闪烁
- asp.net - 为什么部署中只有一部分 pod 启动成功?
- r - 如何在 R 中一次命名多个列表中的对象?
- go - Golang 服务器发送事件 - 服务器发送事件处理程序是否不断调用自己?
- microsoft-graph-api - 通过 Microsoft Graph SDK 更新时,架构扩展值始终为 NULL
- javascript - 如何在 React Native 中共享容器截图 | 安卓博览会