How to update array inside object in mongodb?

by dalton_moen , in category: PHP Databases , 2 years ago

How to update array inside object in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by cortez.connelly , 2 years 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.

by raphael_tillman , 8 months ago

@dalton_moen 

To update an array inside an object in MongoDB, you can use the positional $ operator along with the update methods like updateOne() or updateMany(). Here's an example:


Suppose you have a collection called users with the following documents:


{ _id: 1, name: "John", scores: [80, 90, 95] }, { _id: 2, name: "Jane", scores: [70, 85, 90] }


To update the second element of the scores array for the user with _id 1, you can use the positional $ operator in the update operation:


db.users.updateOne( { _id: 1 }, { $set: { "scores.1": 87 } } )


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


You can also use other update operators like $push, $pull, $addToSet, etc., to add, remove, or modify array elements. For example, to add a new score of 78 to the scores array for the user with _id 2, you can use the $push operator:


db.users.updateOne( { _id: 2 }, { $push: { scores: 78 } } )


This will add the score 78 to the end of the scores array for the user with _id 2.


You can also use more complex query conditions or array filters to update specific elements of the array based on certain criteria. MongoDB provides various powerful update operators to handle different array update scenarios.


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