-1

Schema example:

_id: ObjectId
list: [{field: String}]

If I want to add an array of objects into list - how can I do that?
E.g. I have document like here:

{
  _id: 1
  list: [
    {field: "value1"}, {field: "value2"}
  ]
}

And I want to add into the list this array:

[{field: "val3"}, {field: "val4"}, {field: "val5"}]

Is there a way to do it?

Maksim Nesterenko
  • 5,661
  • 11
  • 57
  • 91

2 Answers2

2

You can use the $push operator together with $each to add all the items to an array in MongoDB:

db.collection.update({_id: 1}, { $push: { list: { $each: [{field: "val3"}, {field: "val4"}, {field: "val5"}]}}});
vladzam
  • 5,462
  • 6
  • 30
  • 36
0

To add objects into the array, you can use push function

var newFields  = [{field: "val3"}, {field: "val4"}, {field: "val5"}];
list.push(newFields);    
codeMan
  • 5,730
  • 3
  • 27
  • 51