简体   繁体   中英

mongodb update nested array from a array

I have a array in mongodb document.

 {
  _id: 1,
  jobs:[
   {
     _id:1,
     time: "08:00",
     status: "pending",
     user: 'user1'
   },
   {
     _id:2,
     time: "09:00",
     status: "pending",
     user: 'user1'
   },
   {
     _id:3,
     time: "07:30",
     status: "done",
     user: 'user2'
   }
]
}

now I have a updated jobs array like this.

jobs:[
   {
     _id:1,
     time: "10:00",
     status: "done"
   },
   {
     _id:2,
     time: "11:00",
     status: "done"
   }
]

updated document should like this

{
  _id: 1,
  jobs:[
   {
     _id:1,
     time: "10:00", // updated
     status: "done" // updated
     user: 'user1'
   },
   {
     _id:2,
     time: "11:00", // updated
     status: "done", // updated
     user: "user1"
   },
   {
     _id:3,
     time: "07:30",
     status: "done",
     user: 'user2'
   }
]
}

I tried using update and $set and no luck so far

how do I update the only the values in the updated array in to the mongodb document? thanks in advance

One option is using an update with a pipeline:

  1. Add the new data into the document as newData
  2. Using a $map to loop over the jobs items, for each item merge it with the matching item in newData .
db.collection.update(
  {_id: 1},
  [{$addFields: {
      newData: [
        {_id: 1, time: "10:00", status: "done"},
        {_id: 2, time: "11:00", status: "done"}
      ]
    }
  },
  {$project: {
      jobs: {
        $map: {
          input: "$jobs",
          in: {
            $mergeObjects: [
              "$$this",
              {$arrayElemAt: ["$newData", {$indexOfArray: ["$newData._id", "$$this._id"]}]}
            ]
          }
        }
      }
    }
  }
])

See how it works on the playground example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM