How to rename a field inside an array with database commands?

Disclaimer: Even though similar, not the same as MongoDB rename database field within array.

I want to change the key of a field from name to title with database commands and NOT the shell. I found out that using $rename is not possible inside an array. So I turned to $set and $unset and created this:

db.runCommand({
    update: 'apps',
    updates: [
        {
            q: {versions: {$elemMatch: {title: {$exists: false}}}},
            u: {
                $set: {'versions.$.title': '$name'}
            },
            multi: true
        },
        {
            q: {versions: {$elemMatch: {name: {$exists: true}}}},
            u: {
                $unset: {'versions.$.name': ''}
            },
            multi: true
        }
    ]
})

This works somewhat. It does all I want but it changes every title/name to the string "$name" instead of the value of the field name.

I also tried this:

db.runCommand({
    update: 'apps',
    updates: [
        {
            q: {versions: {$elemMatch: {title: {$exists: false}}}},
            u: {
                $set: {
                    versions: {
                        $map: {
                            input: "versions",
                            as: 'each',
                            in: {
                                "title": "$$each.name"
                            }
                        }
                    }
                }
            },
            multi: true
        },
        {
            q: {versions: {$elemMatch: {name: {$exists: true}}}},
            u: {
                $unset: {'versions.$.name': ''}
            },
            multi: true
        }
    ]
})

But that just results in [The dollar ($) prefixed field '$map' in 'versions.$map' is not valid for storage.]. How would I go about renaming a field inside an array?

Below is a minified version of my apps collection for reference. I literally only want to change every key called name into title.

[{
  identifier: "x",
  versions: [
    {
      name: "test_name"
      version: "x.x.x"
    },
    {
      name: "test_name"
      version: "x.x.x"
    },
  ]
},
{
  identifier: "y",
  versions: [
    {
      name: "test_name2"
      version: "x.x.x"
    },
    {
      name: "test_name2"
      version: "x.x.x"
    },
  ]
}, ... ]


Read more here: https://stackoverflow.com/questions/66262183/how-to-rename-a-field-inside-an-array-with-database-commands

Content Attribution

This content was originally published by leonheess at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: