Home > database >  How to use the mongo shell update all the elements in an array?
How to use the mongo shell update all the elements in an array?

Time:09-29

Pradb> Db. T1226_1. The find ()
{" _id ": 1," grades ": [95, 92, 90]}
{" _id ": 2," grades ": [98, 100, 102]}
{" _id ": 3," grades ": [95, 110, 100]}

Pradb> Db. T1226_1. Find ({grades: {$gte: 100}});
{" _id ": 2," grades ": [98, 100, 102]}
{" _id ": 3," grades ": [95, 110, 100]}

* * * if you want to put the above array & gt; Elements are updated to 333=100, can use the following command, but seen from the results can only update each document first & gt; The element of=100
Pradb> Db. T1226_1. Update ({grades: {$gte: 100}}, {$set: {" grades. $" : 333}}, {multi: true})
WriteResult ({" nMatched ": 2," nUpserted ": 0," nModified ": 2})

Pradb> Db. T1226_1. The find ()
{" _id ": 1," grades ": [95, 92, 90]}
{" _id ": 2," grades ": [98, 333, 102]} & lt; - the first only updated every document to meet the conditions of the element
{" _id ": 3," grades ": [95, 333, 100]}

If you want to update all at the same time & gt;=100 elements, use what method can be implemented?

CodePudding user response:

https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/
Official document it gave way, verification is successful, give points
Db. T1226_1. Update (
{},
{$set: {" grades. $/element ": 333}},
{multi: true,
ArrayFilters: [{" element ": {$gte: 100}}]
}
)
  • Related