0

I have this simple collection of students:

{
    "_id": "btv7865reVGlksabv",
    "students": [
        {
            "name": "John",
            "age": 30
        },
        {
            "name": "Henry",
            "age": 25
        }
    ]
}

Now I want to push new students into this array:

const newStudents = [
    {
        "name": "Mike",
        "age": 22
    },
    {
        "name": "Kim",
        "age": 20
    }
]

What I tried so far is:

Students.update(
    {
        "_id": "btv7865reVGlksabv"
    },
    {
        $push: {
            "students": newStudents
        }
    }
);

The above query doesn't update my collection for some reason. Can anyone help me correct this query?

0

2 Answers 2

2

Chain up $push with $each

db.collection.update({
  "_id": "btv7865reVGlksabv"
},
{
  $push: {
    "students": {
      $each: [
        {
          "name": "Mike",
          "age": 22
        },
        {
          "name": "Kim",
          "age": 20
        }
      ]
    }
  }
})

Mongo Playground

Sign up to request clarification or add additional context in comments.

Comments

0

Maybe something like this:

db.collection.update({},
[
 {
  $addFields: {
  students: {
    $concatArrays: [
      "$students",
      [
        {
          name: "New1",
          age: "New1"
        },
        {
          name: "New2",
          age: "New2"
        }
      ]
    ]
  }
}
}
])

Explained:

Use $addFileds->$concatArrays to update via aggregation pipeline ( 4.2+) to add the elements from your new array to the already existing array ...

Playground

Comments

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.