【问题标题】:how to find and rename field name in mongodb 3.2如何在 mongodb 3.2 中查找和重命名字段名称
【发布时间】:2017-03-08 18:52:26
【问题描述】:

如何在 MongoDB 中重命名字段名称?

我想将所有以$开头的字段名替换为&。

谢谢!

【问题讨论】:

    标签: json mongodb mongodb-query


    【解决方案1】:

    我看到了一些链接并为您的问题制定了适当的解决方案

    首先你需要得到你的所有列,你可以用 MapReduce 做到这一点:

    mr = db.runCommand({
      "mapreduce" : "my_collection",
      "map" : function() {
        for (var key in this) { emit(key, null); }
      },
      "reduce" : function(key, stuff) { return null; }, 
      "out": "my_collection" + "_keys"
    });
    

    然后在结果集合上运行 distinct 以找到所有键:

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

    并重命名所有匹配的列

    columns.forEach(function(columnName) {
        if (columnName.indexOf('$') == 0) {
            var newColumnName = columnName.replace('$', '&');
            rename_query = { '$rename': {} };
            rename_query['$rename'][columnName] = newColumnName;
            db.my_collection.updateMany({}, rename_query)
        }
    })
    

    参考链接是

    MongoDB Get names of all keys in collection

    MongoDB $rename javascript variable for key name

    【讨论】:

    • 其实我不知道字段名,只知道有$开头的字段。有没有我们可以使用的类似运算符?
    • 我已根据您的要求更新了答案
    • 谢谢@gaurav,我还有另一个问题,数组中的字段名很少。
    • 下面是示例文档 { "_id" : ObjectId("123"), "op" : "command", "ns" : "test.test", "command" : { "aggregate" :“测试”,“管道”:[{“$match”:{“标识符”:“U1”,“观众”:/^agent$/i}},{“$limit”:1}],跨度>
    猜你喜欢
    • 2021-06-08
    • 1970-01-01
    • 2018-05-24
    • 2020-09-25
    • 2015-09-20
    相关资源
    最近更新 更多