skip to Main Content

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?

2

Answers


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

    Login or Signup to reply.
  2. Chain up $push with $each

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

    Mongo Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search