首页 > 解决方案 > 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.

标签: node.jsmongodb

解决方案


这里有两件事,

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


推荐阅读