根据其他字段将新字段添加到集合中

时间:2020-02-07 15:08:39

标签: mongodb pipeline

“ MongoDB版本:4.2 操作系统:OSX

我的家庭收藏集中有以下文档:

{
    "_id" : "xxxx",
    "name" : "home1",
    "homeName" : "home1",
    "allowAdminActions" : true,
    "_created_at" : ISODate("2020-02-07T14:55:06.819Z"),
    "_updated_at" : ISODate("2020-02-07T14:55:12.356Z"),
    "_p_Owner" : "xxxxx",
    "allowUpdate" : false,
    "devicesConfig" : {
        "hello" : 1,
        "deviceConfig" : {
            "data" : [
                {
                    "type" : "CommunicationConfig",
                    "wifiName" : "wifitest",
                    "wifiPassword" : "wifipassword"
                }
            ]
        }
    }
}

然后,我想创建一个从wifiName字段推断出来的名为devicesConfig的字段:

db.Home.update(
    {},
    [
        {"$project": {"connConfig": {$arrayElemAt: ["$devicesConfig.deviceConfig.data", 0]}}},
        {"$set":  {"wifiName": "$connConfig.wifiName"}}
    ],
    false,
    true
)

预期结果将是:

{
    "_id" : "xxxx",
    "name" : "home1",
    "homeName" : "home1",
    "allowAdminActions" : true,
    "_created_at" : ISODate("2020-02-07T14:55:06.819Z"),
    "_updated_at" : ISODate("2020-02-07T14:55:12.356Z"),
    "_p_Owner" : "xxxx",
    "allowUpdate" : false,
    "devicesConfig" : {
        "hello" : 1,
        "deviceConfig" : {
            "data" : [
                {
                    "type" : "CommunicationConfig",
                    "wifiName" : "wifitest",
                    "wifiPassword" : "wifipassword"
                }
            ]
        }
    },
    "wifiName" : "wifitest"
}

实际结果:

{
    "_id" : "xxxxx",
    "connConfig" : {
        "type" : "CommunicationConfig",
        "wifiName" : "testwifi",
        "wifiPassword" : "testpassword"
    },
    "wifiName" : "testwifi"
}

如何避免update操作删除所有其他未指定的字段?

谢谢!

1 个答案:

答案 0 :(得分:0)

您应该将$addFields$project结合使用:

  id other_col  period
0  A         X  winter
1  B         Y  summer
2  C         Z     NaN
3  D         D  spring