0

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?

1 Answer 1

1

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
      }
 })
Sign up to request clarification or add additional context in comments.

3 Comments

Guess I was taking a shortcut. Still would be cool to be able to do that :)
@vfxcode then how would you update the whole object :-)? This behavior is expected.
I was just referring to the same way you can use $set to do a basic update and only supply the changing fields: db.test.update({"_id" : ObjectId("553c6c9216a0c2f8cbb35e7d")}, {$set: {'school':'yale', 'class':'economics101'}}). It doesn't replace the whole document.

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.