3

I have the following document:

{
 "name" : "student_1",
 "courses" : [
 {
 "name" : "Algebra",
 "grades" : [ 98, 96, 92 ]
 },
 {
 "name" : "Computers",
 "grades" : [ 80 ]
 }
 ]
}

How can I update the grades of a specified course? For example, I want to increment some test in the course Algebra by 10 points.

asked Sep 7, 2015 at 7:10

1 Answer 1

7

'some test', so let's say you want to add 10 to 96 :

db.student.update({name:'student_1','courses.name':'Algebra'},{$inc:{"courses.$.grades.1":10}})

In the find part, you point to the courses with name 'Algebra'. The .$ points you to that found element. Of that found element, it will change the second (.1) value in the grades array. Using $, you don't need to know the position of the course in the array.

András Váczi
31.8k13 gold badges103 silver badges152 bronze badges
answered Sep 8, 2015 at 5:00
2
  • 1
    The $ gives me the first element, what if I want to update Computers course? Do I have to know the position of the course in the array? Commented Sep 8, 2015 at 5:28
  • In the find part, you point to the courses with name 'Algebra'. The .$ points you to that found element. Of that found element, it will change the second (.1) value in the grades array. Using ,ドル you don't need to know the position of the course in the array. Commented Sep 8, 2015 at 7:05

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.