Corey Burnett
Corey Burnett

Reputation: 7340

How to update mongodb document with complex field from another document?

I have the following 2 mongodb documents:

{
  "id" : "[email protected]",
  "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": "[email protected]",
  "Sales Data" : {
    "Company" : "Your Company",
    "PhoneNumber" : "",
    "City" : "",
    "State" : ""
  }
}

I am trying to figure out how to write a mongodb update statement that will update the "Sales Data" field of the second document with the "Sales Data" field data from the first document. Even if I have to manually construct the update statement that is fine. I just can't figure out the syntax. I tried something like this but it doesn't work

db.getCollection('MyCollection').update({id: "[email protected]"}, {$set: {"Sales Data": "???"});

Upvotes: 0

Views: 139

Answers (1)

Corey Burnett
Corey Burnett

Reputation: 7340

With the help of @chridam I was able to figure it out. I just used the mongo shell and wrote a small script that did the trick. It looked like this:

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

db2 = connect("instance2Url/myDB2", "myUserName", "myPassword");
coll2 = db2.getCollection("myCollection");
coll2.updateOne({id:"[email protected]"}, {$set: {"Sales Data": salesData}});

Upvotes: 0

Related Questions