【问题标题】:How to add new field and copy the value from existing field if its not null in mongo using a query如果使用查询在mongo中不为空,如何添加新字段并从现有字段复制值
【发布时间】:2021-06-28 16:29:43
【问题描述】:

我想根据其他字段的值向 mongo 集合中的所有文档添加新字段,前提是它们不为空。我已经编写了一个脚本来执行此操作,但是我们可以使用一个查询来完成此操作吗?

样本数据:

[{
        "outdoor": {
            "location": {
                "type": "Point",
                "coordinates": [
                    -92.41151,
                    35.11683
                ]
            }
        },
"address": {    "street1" : "Street 1",
        "postalCode" : "95050",
        "state" : "CA",
        "locality" : "City 1",
        "countryCode" : "US"},
"customerId":"8047380094"

    },
    {
        "outdoor": {
            "location": {
                "type": "Point",
                "coordinates": [
                    -89.58342,
                    36.859161
                ]
            }
        },
        "customerId":"8047380094"
    },
    {
        "address": {

                "street1" : "Street 1",
        "postalCode" : "95050",
        "state" : "CA",
        "locality" : "City 1",
        "countryCode" : "US"
        },
      "customerId":"8047380094"
    }]

需要添加以下新字段:

  1. new_address - 如果地址数据不为空,则将地址数据复制到此字段中
  2. new_location - 如果outdoor.location 不为空,则将其复制到该字段中

感谢任何帮助。

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您可以使用 Mongo Aggregation Pipeline 支持从 MongoDB 版本 4.2 开始提供的更新命令

    db.collection.updateMany({
      "address": {
        "$ne": null
      }
    },
    [
      {
        "$set": {
          "new_address": "$address"
        },
      }
    ])
    
    db.collection.updateMany({
      "outdoor.location": {
        "$ne": null
      }
    },
    [
      {
        "$set": {
          "new_location": "$outdoor.location"
        },
      }
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-15
      • 2017-06-24
      • 1970-01-01
      • 2019-05-02
      • 2019-08-20
      • 2021-12-05
      • 2017-09-01
      • 1970-01-01
      相关资源
      最近更新 更多