使用新字段更新 Mongodb 集合中的所有文档

问题描述 投票:0回答:3

我有一个名为员工的集合,其中包含类似的文档。

{
first_name:"john",
last_name:"doe"
}

我想运行一个更新查询,添加一个新字段,如

{name:'john doe'}

我知道可以这样做

db.employees.find({}).forEach(doc=>db.employees.update({"_id":doc._id},{$set:{name:doc.first_name+"-"+doc.last_name}}))

但是当我使用 mongo compass 和在 atlas 中运行的数据库时,它需要花费很多时间。

mongodb mongodb-query mongo-shell mongodb-update
3个回答
3
投票

这是一种使用

update
聚合管道来实现的方法。

db.employees.update({
  "first_name": {"$exists": true},
  "last_name": {"$exists": true},
  "name": {"$exists": false}
},
[
  {
    "$set": {
      "name": {
        "$concat": ["$first_name", " ", "$last_name"]
      }
    }
  }
],
{"multi": true}
)

mongoplayground.net 上尝试一下。


0
投票

使用 db.collection.updateMany() 更新与指定过滤器匹配的所有文档。

例如: 要更新 example_airbnb.listingsAndReviews 集合中的所有文档,以更新 security_deposit 小于 100 的位置:

    use sample_airbnb

db.listingsAndReviews.updateMany(
  { security_deposit: { $lt: 100 } },
  {
    $set: { security_deposit: 100, minimum_nights: 1 }
  }
)

更新操作使用 $设置 运算符将 security_deposit 字段的值更新为 100,将 minus_nights 字段的值更新为 1。

这取自:https://www.mongodb.com/docs/mongodb-shell/crud/update/


0
投票

db.collection.updateMany(filter, update, options)
=> 更新很多

db.employees.updateMany({
  "first_name": {"$exists": true},
  "last_name": {"$exists": true},
  "name": {"$exists": false}
},  
{
  "$set": {
    "name": { "$concat": ["$first_name", "-", "$last_name"] }
  }
}, 
{ upsert: true}
)

!不要忘记首先选择您的数据库。

    

© www.soinside.com 2019 - 2024. All rights reserved.