如何使用其他文档中的复杂字段更新mongodb文档?

时间:2017-03-20 13:23:53

标签: mongodb

我有以下2个mongodb文件:

{
  "id" : "me@something.com",
  "Sales Data" : {
    "Company" : "Some Company",
    "PhoneNumber" : "301-555-1212",
    "City" : "Baltimore",
    "State" : "MD",
    "Orders" : {
      "0" : {
        "ProductId" : "ABC",
        "Quantity" : "3"
      },
      "1" : {
        "ProductId" : "DEF",
        "Quantity" : "2"
      }
    }
  }
}

{
  "id": "you@company.com",
  "Sales Data" : {
    "Company" : "Your Company",
    "PhoneNumber" : "",
    "City" : "",
    "State" : ""
  }
}

我试图找出如何编写mongodb update语句,该语句将使用第一个文档中的“Sales Data”字段数据更新第二个文档的“Sales Data”字段。即使我必须手动构造更好的更新语句。我只是无法弄清楚语法。我试过这样的东西,但它不起作用

db.getCollection('MyCollection').update({id: "you@company.com"}, {$set: {"Sales Data": "???"});

1 个答案:

答案 0 :(得分:0)

在@chridam的帮助下,我能够弄明白。我刚刚使用了mongo shell并编写了一个小脚本来完成这个技巧。它看起来像这样:

db1 = connect("instance1Url/myDb1","myUserName","myPassword");
coll1 = db1.getCollection("myCollection");
salesData = coll1.findOne({id:"me@something.com"})["Sales Data"];

db2 = connect("instance2Url/myDB2", "myUserName", "myPassword");
coll2 = db2.getCollection("myCollection");
coll2.updateOne({id:"you@company.com"}, {$set: {"Sales Data": salesData}});