0

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?

1
  • @JohnnyHK Well, I guess that's the answer. Write it here as an answer and I'll accept it. Commented Dec 12, 2018 at 18:39

1 Answer 1

2

$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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.