“ 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
操作删除所有其他未指定的字段?
谢谢!
答案 0 :(得分:0)
您应该将$addFields与$project结合使用:
id other_col period
0 A X winter
1 B Y summer
2 C Z NaN
3 D D spring