What is the best way to do adhoc updates directly on the database?

Hello Everyone,

I am still new to MongoDB, coming from an SQL server background. I have a good idea how to query everything but what is the best way to do updates directly in the database? We are using Atlas hosted DBs and the problem I encounter today was trying to change the case of a string field, some documents had pascal while others were lower. I needed them to all be lower case so I was trying to figure out how to do that in compass, the solution I came up with was using the monghsh terminal with a db.collection.updateMany command. Is there a way to do this using the Aggregation Pipeline UI in compass instead? Here is my mongosh command:

db.collection.updateMany({},
[
  {
    $set: {
      Status: {
        $toLower: "$Status"
      }
    }
  }
])

You would do the same $set in you pipeline and add a final $merge stage.

Ok, did not realize that was possible. Thanks. I read some more on that operation and found this warning about “documents may get updated multiple times or the operation may result in an infinite loop” and a Halloween problem. Is that something I should worry about? Does it only apply to the Aggregation Pipeline or would this same problem possible happen using the db.collection.updateMany command?

That is why you do not want to do that without a $match stage that make sure documents get update only once.

In your case, it is easy to write a $match that only selects document that have an upper case in the Status field. This way, if the document is fetched twice it won’t match the second time and won’t be updated over and over.

Thanks for remembering us of the warning.