I have a document to Mongodb update array of objects like this:
{
"_id" : 5,
"quizzes" : [
{ "wk" : 1, "score" : 10 },
{ "wk" : 2, "score" : 8 },
{ "wk" : 5, "score" : 8 }
]
}
And I want to add new field in each object of quizzes array. The expected result should be
{
"_id" : 5,
"quizzes" : [
{ "wk" : 1, "score" : 10, "day": 1 },
{ "wk" : 2, "score" : 8, "day": 2 },
{ "wk" : 5, "score" : 8, "day": 3 }
]
}
Any solution for this.
Sinto
3,97712 gold badges41 silver badges74 bronze badges
-
1how will you decide the order of the day?Rahul Sharma– Rahul Sharma2018年03月15日 06:29:32 +00:00Commented Mar 15, 2018 at 6:29
1 Answer 1
You can use Aggregation Framework:
db.col.aggregate([
{
$unwind: {
path: "$quizzes",
includeArrayIndex: "quizzes.day"
}
},
{
$group: {
_id: "$_id",
quizzes: {
$push: {
"score" : "$quizzes.score",
"wk" : "$quizzes.wk",
"day" : { $add: [ "$quizzes.day", 1 ] }
}
}
}
},
{
$out: "col"
}
])
To assign indexes to each element you can use $unwind with includeArrayIndex option. Those indexes start with 0 so we have to use $add to start with 1. Then you can group back by your _id property and use $out to save aggregation results to your collection.
answered Mar 15, 2018 at 6:41
mickl
50.1k9 gold badges71 silver badges99 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Dinesh Sathrasala
can I do it without $project
mickl
@DineshSathrasala without $project you'll get 0,1,2 instead of 1,2,3 however you can move that logic into $group like in edited answer
lang-js