Veit's Blog

Hej! đź‘‹ Welcome to my curated space of insights on software development and the tapestry of life.

Rename fields in MongoDB documents

2019-05-22

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.