MongoDB - 数组元素作为变量

时间:2018-03-08 16:52:14

标签: database mongodb mongodb-query

让我们说这是同一份文件:

{
"_id" : 1.0,
"custname" : "metlife",
"address" : {
    "city" : "Bangalore",
    "country" : "INDIA"
 }
}

如果我想在本文档中添加一个额外的字段,如下所示:

db.customers.updateMany(
  {"address.country":"INDIA"},
  {$push : {city: "$address.country"}}

)

导致更新错误:

{
"_id" : 1.0,
"custname" : "metlife",
"address" : {
    "city" : "Bangalore",
    "country" : "INDIA"
 },
 "city" : "$address.city"
}

而不是:

{
"_id" : 1.0,
"custname" : "metlife",
"address" : {
    "city" : "Bangalore",
    "country" : "INDIA"
 },
 "city" : "Bangalore"
}

如何达到上述效果?

3 个答案:

答案 0 :(得分:1)

您目前无法在更新中引用其他字段值(更多here)。聚合框架中有一种解决方法(使用$out),但它将替换整个集合。

我认为您可以考虑在您的案例中使用$rename。它不会添加新字段,但可以将city移动到文档的顶层。

db.customers.updateMany({"address.country":"INDIA"}, {$rename: {"address.city": "city"}})

将为您提供以下结构:

{ "_id" : 1, "custname" : "metlife", "address" : { "country" : "INDIA" }, "city" : "Bangalore" }

答案 1 :(得分:0)

喜欢@mickl说:你目前无法在更新中引用其他字段值, 你必须遍历你的集合来更新文档,试试这个:

db.eval(function() { 
    db.collection.find({"address.country":"INDIA"}).forEach(function(e) {
        e.city= e.address.city;
        db.collection.save(e);
    });
});

请记住,这将阻止数据库,直到完成所有更新。

答案 2 :(得分:-1)

试试这个

db.customers.updateMany(
  {"address.country":"INDIA"},
  {$push : {city: "address.country"}}

)

删除$ sign