0

Here's what my JSON response looks like:

"_id" : 537,
    "quizzes" : [
        {
            "wk" : 1,
            "score" : [
                10
            ]
        },
        {
            "wk" : 2,
            "score" : [
                8
            ]
        },
        {
            "wk" : 3,
            "score" : [
                5
            ]
        },
        {
            "wk" : 4,
            "score" : [
                6
            ]
        }
    ]
}

I'm trying to update the score array inside one of the objects, here's my attempt at it:

db.collection('connect').update({_id: id}, {$push: { quizzes[0]: { score: 89  }  }});
1
  • What would be the expected result? If you wish to update the score array so that it still remains a single element array then consider using the update operator modifier "$set": { "quizzes.0.score.0": 89 } as mentioned in my solution below. Commented Jun 20, 2015 at 22:12

2 Answers 2

2

Try the following update:

db.collection("connect").update(
    {
        "_id": id            
    }, 
    {
        "$set": { 
            "quizzes.0.score.0": 89    
        }
    }
);

which uses the dot notation to access the elements of an array and to access the fields of an embedded document.

To access an element of an array by the zero-based index position, concatenate the array name with the dot (.) and zero-based index position, and enclose in quotes:

'<array>.<index>'
Sign up to request clarification or add additional context in comments.

Comments

1

I think you are looking for

db.collection('connect').update({_id: id}, {$set: { "quizzes.0.score":89}  })

A better way to do it is to not reply on the index of the quizzes array and use the "wk" attribute

db.collection('connect').update({_id: id,quizzes:{$elemMatch:{"wk":1}}}, {$set: { quizzes.$.score: 89  }  }})

3 Comments

The brackets are giving me a syntax error: SyntaxError: Unexpected token [
$ is the positional operator. Which replaces the hard coded 0 in the previous query
That seems to not be working for me, can you check this question I posted? stackoverflow.com/questions/30961717/…

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.