如果mongo中的值不为null,如何使用查询添加新字段并从现有字段中复制值



我想根据其他字段的值向mongo集合中的所有文档添加新字段,前提是这些字段不为null。我已经写了一个脚本来完成这项工作,但有没有一个查询可以完成这项任务?

样本数据:

[{
"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不是null,则将其复制到此字段中

感谢您的帮助。

您可以使用Mongo聚合管道支持从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"
},
}
])

最新更新