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
Maybe something like this:
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
Chain up
$push
with$each
Mongo Playground