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
-
What is your expected result? A document with _id:1, in which jobs with _id:1, _id:2 are updated and job with _id:3 stayed the same?nimrod serok– nimrod serok2022年09月10日 13:42:57 +00:00Commented Sep 10, 2022 at 13:42
1 Answer 1
One option is using an update with a pipeline:
- Add the new data into the document as
newData - Using a
$mapto loop over thejobsitems, for each item merge it with the matching item innewData.
EDIT (consider partial match):
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",
{$cond: [
{$gte: [{$indexOfArray: ["$newData._id", "$$this._id"]}, 0]},
{$arrayElemAt: ["$newData", {$indexOfArray: ["$newData._id", "$$this._id"]}]},
]}
]}
]}
}}
}}
])
See how it works on the playground example
answered Sep 10, 2022 at 13:56
nimrod serok
16.1k2 gold badges15 silver badges36 bronze badges
Sign up to request clarification or add additional context in comments.
8 Comments
Lahiru Supun
that's amazing. thanks. I was thinking about this all day
Lahiru Supun
how do I use this with mongoose updateOne?
nimrod serok
The same. Just replace update with updateOne
Lahiru Supun
it doesn't work!. it just replaced all the elements in the array. sorry
nimrod serok
I just don't like to be wrong. When I'm wrong I'm working extra fast to be right
|
lang-js