I have a document like below
{
"_id" : ObjectId("5d0768f50557b958f0c6c9cf"),
"list" : [
"abc",
"xyz",
"mno"
],
"timestamp" : "2019-06-17T10:18:29.986Z"
}
I need to update it like this below
{
"_id" : ObjectId("5d07711dbf557c3d1878ff97"),
"list" : [
{
"name" : "abc",
"type" : "car",
"color" : "red"
},
{
"name" : "xyz",
"type" : "bike",
"color" : "black"
},
{
"name" : "mno",
"type" : "auto",
"color" : "blue"
}
],
"timestamp" : "2019-06-17T10:53:17.537Z"
}
Here I need to add two more fields ie, "type" & "color" including "name" as shown in above code.
Is it good to use MongoDB aggregation as I need to deal with array and objects.
Aggregation is not the answer here, when you need to update your data you need use update methods
For example for your case:
db.collection.updateOne(
{_id: ObjectId("5d07711dbf557c3d1878ff97")},
{
$set: {
time_stamp: Date.now()
},
$push: {
list: {$each:
[{
"name" : "xyz",
"type" : "bike",
"color" : "black"
},
{
"name" : "mno",
"type" : "auto",
"color" : "blue"
}]},
}
}
)
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.