Rename fields in MongoDB documents

Often the structure of domain objects needs to be updated to reflect some recent business case changes in your app. A lot of devs I worked with are not annoyed with different docs and domain objects. But I like to reflect changes in the domain object in the underlying collection documents.

I have a working snippet in my toolbox that worked for years. But as it uses cursors it was painfully slow. Somehow until today I don't thought about using db.collection.updateMany() and the $rename operator.

db.getCollection("mycollection")  
    .updateMany(
        {/*also filtering is possible here*/ },
        {
            $rename: {
                "properties.verified": "verified"
            }
        }
    )       

The query moves the nested field verified in properties to verified. And it's blazing fast.