How can we update all elements that match the condition in all arrays in one ope

84 views
Skip to first unread message

olis...@gmail.com

unread,
Jan 20, 2018, 7:11:05 AM1/20/18
to mongodb-user
How can we update all elements that match the condition in all arrays in one operation

***we filter out all documents whose arrays has element equal to or greater than 100
pradb>db.t1226_1.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 ] }

***Now we need to update all elements equal to or greater than 100 to 333 and we invoke the following update operations
pradb>db.t1226_1.update({grades:{$gte:100}},{$set:{"grades.$":333}},{multi:true})
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

***From the result we can see that only the first element which is equal to or greater than 100 in each array is updated while the rests remains unchanged
pradb>db.t1226_1.find()
{ "_id" : 1, "grades" : [ 95, 92, 90 ] }
{ "_id" : 2, "grades" : [ 98, 333, 102 ] }   <---only 100 is updated to 333, 102 remains unchanged
{ "_id" : 3, "grades" : [ 95, 333, 100 ] }   <---only 110 is updated to 333,100 remains unchanged

If we intend to update all elements which are greater than 100 in one operation, how can I do it?

Wan Bachtiar

unread,
Jan 21, 2018, 8:18:37 PM1/21/18
to mongodb-user

If we intend to update all elements which are greater than 100 in one operation, how can I do it?

Hi,

In MongoDB v3.6, you can specify arrayFilters to determine which array elements ot update.
For example, given your above documents you can do :

db.collection.update({grades:{$gte:100}}, 
                     {$set:{"grades.$[element]":333}}, 
                     {arrayFilters:[{element: {$gte:100}}], multi:true})

See also command update

Regards,
Wan.

Reply all
Reply to author
Forward
0 new messages