【问题标题】:How to insert field in already existing nested documents in mongodb?如何在MongoDB中已经存在的嵌套文档中插入字段?
【发布时间】:2018-09-18 13:13:09
【问题描述】:

我有以下文档结构。

{ 
    "_id" : ObjectId("585a985f67962d91c0f3a1f6"), 
    "Email" : "abc@gmail.com", 
    "PhoneNumber" : "9999999999", 
    "TwoFactorEnabled" : false, 
    "LockoutEndDateUtc" : null, 
    "LockoutEnabled" : true, 
    "AccessFailedCount" : NumberInt(0), 

    "DisplayName" : "Nilesh Guria", 
    "CreatedOn" : ISODate("2016-12-21T14:57:35.379+0000"), 
    "UpdatedOn" : ISODate("2018-09-17T21:32:16.027+0000"),  
    "Wallet" : {
        "Balance" : 1000,
        "UnbilledUsage": 100
    }
}

我想在所有此类文档的“钱包”字段中添加一个名为“CustomerCredit”的字段,默认值为 0。如何做到这一点?

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:
    db.collection("collectionName")
      .updateMany({ "Wallet.CustomerCredit": { $exists: false }},
              { $set:{ "Wallet.CustomerCredit": 0 }});
    

    【讨论】:

      【解决方案2】:

      来自 python shell。

      db.collection.update_many({"$set": {"Wallet.CustomerCredit": 0}})
      

      您可以使用 update_many,因为 update 现已弃用。 来自 mongoshell

      db.collection.updateMany({},{$set: {"Wallet.CustomerCredit": 0}})
      

      【讨论】:

        【解决方案3】:

        试试这样的:

        db.collection.aggregate([
            {
                $addFields{
                     "Wallet.CustomerCredit": 0
                }
            }
        ])
        

        docs

        【讨论】:

          猜你喜欢
          • 2020-04-10
          • 2020-08-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-02-01
          相关资源
          最近更新 更多