MongoDB Shell Script Update all field names where there is a space in the field name

Using MongoDBshell script 3.2, how can I update all fields in which field names have space replace those with underscore?

{
"Some Field": "value",
"OtherField" :"Value",
"Another Field" : "Value"
}

update the above document below

{
"Some_Field": "value",
"OtherField" :"Value",
"Another_Field" : "Value"
}

you can rename the field with something like this

db.CollectionName.update( { _id: 1 }, { $rename: { 'nickname': 'alias', 'cell': 'mobile' } } )

The tricky part here filteris how to figure filterout where there is a space in the field name

+4
source share
2 answers

. -, . , , . $rename. mapReduce, .

mapReduce _id :

mr = db.runCommand({
    "mapreduce": "CollectionName",
    "map": function() {
        var regxp = /\s/;
        for (var key in this) { 
            if (key.match(regxp)) {
                emit(key, null); 
            }
        }
    },
    "reduce": function() {}, 
    "out": "filtered_keys"
})

, :

db[mr.result].distinct("_id")
["Some Field", "Another Field"]

, , , , , . :

var update = {
    "$rename": {
        "Some Field": "Some_Field",
        "Another Field": "Another_Field"        
    }
}

,

var update = { "$rename": {} };
db[mr.result].distinct("_id").forEach(function (key){
    update["$rename"][key] = key.replace(/ /g,"_");
});

db.CollectionName.update({ }, update, false, true );
+1

@chridam .

, .

mr = db.runCommand({
    "mapreduce": "MyCollectionName",
    "map": function() {
        var regxp = /\s/;
        for (var key in this) { 
            if (key.match(regxp)) {
                emit(key, null); 
            }
        }
    },
    "reduce": function() {}, 
    "out": "filtered_keys"
})

db[mr.result].distinct("_id")

var update = { "$rename": {} };
db[mr.result].distinct("_id").forEach(function (key){
    update["$rename"][key] = key.replace(/\s+/g, "_");
});

//print(update)

db.MyCollectionName.update({ }, update, false, true );
+1

Source: https://habr.com/ru/post/1649863/


All Articles