Scott
Scott

Reputation: 3344

mongoDB update multiple fields in single array element (from form)

I've seen many variations on this question, but none for this specific issue. Consider the following document:

{
    "class" : "english101",
    "students" : [
        {
            "name" : "julie",
            "age" : 32,
            "gpa" : "3.4"
        },
        {
            "name" : "heather",
            "age" : 34,
            "gpa" : "3.8"
        }
    ]
}

I'd like to update BOTH the name and age fields simultaneously. Here's what I'm trying:

db.test.update(
    {
        'class':'english101', 
        'students.name':'julie'
    },
    {
        $set: {
            'students.$': {
                'name':'jules',
                'age':'31'
            }
         }
     }
 )

The result is this:

{
    "class" : "english101",
    "students" : [
        {
            "name" : "jules",
            "age" : "31",
            # GPA IS GONE!
        },
        {
            "name" : "heather",
            "age" : 34,
            "gpa" : "3.8"
        }
    ]
}

The PROBLEM is that instead of the expected update and $set behavior it replaces the whole array item, instead of just updating the supplied fields.

How should I be doing this?

Upvotes: 0

Views: 50

Answers (1)

Salvador Dali
Salvador Dali

Reputation: 222581

In your case you update it with an object, which overwrites everything. Here is a correct approach.

 db.test.update({
      'class':'english101', 
      'students.name':'julie'
 },{
      $set: {
          'students.$.name': 'jules',
          'students.$.age' : 31
      }
 })

Upvotes: 1

Related Questions