rickhg12hs
rickhg12hs

Reputation: 11912

$rename MongoDB field names using $regex in mongo shell?

I've looked at other questions, but none that I've seen want to modify field names with a $regex in a mongo shell. My attempts to use db.collection.update with $rename and a $regex have failed.

I have a collection with documents like this:

{
    "_id" : "CWE-693",
    "Name" : "Protection Mechanism Failure",
    "Description" : "The product does not use or incorrectly uses a protection mechanism that provides sufficient defense against directed attacks against the product.",
    "Modes_Of_Introduction" : [
        "Architecture and Design",
        "Implementation",
        "Operation"
    ],
    "Common_Consequences" : [
        "Bypass Protection Mechanism"
    ]
}

I'd like to rename all of the field names (other than "_id") to eliminate the underscores ("_") so the document instead looks like this:

{
    "_id" : "CWE-693",
    "Name" : "Protection Mechanism Failure",
    "Description" : "The product does not use or incorrectly uses a protection mechanism that provides sufficient defense against directed attacks against the product.",
    "ModesOfIntroduction" : [
        "Architecture and Design",
        "Implementation",
        "Operation"
    ],
    "CommonConsequences" : [
        "Bypass Protection Mechanism"
    ]
}

Is this possible with db.collection.update, with $rename and a $regex? Are there other mongo shell programmatic ways to achieve this?

Upvotes: 0

Views: 225

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

$rename can only be used with plain strings, not regexes.

So you'd have to write code to read a representative doc, iterate over the field names and assemble a $rename operation to execute.

Upvotes: 2

Related Questions