How to update array inside object in mongodb?

by dalton_moen , in category: PHP Databases , 8 months ago

How to update array inside object in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cortez.connelly , 3 months ago

@dalton_moen 

To update an array inside an object in MongoDB, you can use the $set operator along with the $ operator to specify the element of the array that you want to update.


For example, let's say you have a collection called students with the following documents:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
{
  _id: 1,
  name: "John",
  grades: [80, 90, 95]
},
{
  _id: 2,
  name: "Jane",
  grades: [70, 85, 90]
}


To update the second grade of the student with _id 1, you can use the following update operation:

1
2
3
4
db.students.updateOne(
   { _id: 1 },
   { $set: { "grades.1": 87 } }
)


This will update the second element (index 1) of the grades array to 87 for the student with _id 1.


You can also use the $ operator to update multiple elements of an array at once. For example, to update the first and third grades of the student with _id 1, you can use the following update operation:

1
2
3
4
5
db.students.updateOne(
   { _id: 1 },
   { $set: { "grades.$[i]": 87 } },
   { arrayFilters: [ { "i": { $in: [0, 2] } } ] }
)


This will update the first and third elements (index 0 and 2) of the grades array to 87 for the student with _id 1.


Note that you can also use the updateMany() method to update multiple documents at once.


I hope this helps! Let me know if you have any questions.