1

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.
1
  • 1
    how will you decide the order of the day? Commented Mar 15, 2018 at 6:29

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

can I do it without $project
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.