HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

MongoDB update object in Array

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
arrayobjectmongodbupdate

Problem

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.

Solution

'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.

Code Snippets

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

Context

StackExchange Database Administrators Q#114329, answer score: 7

Revisions (0)

No revisions yet.