0

Finding and updating specified field in mongo is quite easy;

User.updateMany({ name: 'Mary' }, { $set: { age: 18 } }, { multi: true })

However it will only find elements that have name set to Mary.

In my case, I want to update every element which field name is longer than 3 characters and field checked is true.

if (name.length > 3 && checked === true) then $set: { age: 18 }

Question: How to do such conditional update in mongo? Thanx!

Community
  • 1
  • 1
Patrickkx
  • 1,740
  • 7
  • 31
  • 60
  • Which version of Mongo are you using? In 3.4+ you can use $strLenCP as part of an aggregation pipeline to query the string length. Then you can use this with the $gt operator – Robert Seaman Mar 18 '19 at 23:29
  • @RobertSeaman Im using mongoose 5+, dunno about mongodb version exactly – Patrickkx Mar 18 '19 at 23:32
  • `.updateMany({ "checked": true, "$expr": { "$gt": [ { "$strLenCP": "$name" }, 3 ] } }, { .. same $set statement` or `{ "checked": true, "$where": "this.name.length > 3" }` for older versions without `$expr`. Note also `{ multi: true }` is "implied" by `updateMany()` and not required. – Neil Lunn Mar 18 '19 at 23:44
  • Either update() or updateMany() can do the job. It depends on what you have in mind. the difference is that update() by default modifies only a single document but if you include the modifier {multi: true}, then it can operate as updateMany which finds and modifies all documents matching the filter. – Lawrence Eagles Mar 14 '20 at 13:25

0 Answers0