格式化MongoDB结果

时间:2016-12-26 13:13:22

标签: mongodb mongodb-query nosql

当我们从集合“Articles”

中获取数据时,MongoDB返回以下JSON数组
[{
    "_id": "id1",
    "description": "Description for article",
    "author": "publisher of article"
}, {
    "_id": "id2",
    "description": "Description for article",
    "author": "publisher of article"
}, {
    "_id": "id3",
    "description": "Description for article",
    "author": "publisher of article"
}]

但是我希望json采用以下格式

[{
    "id1": {
        "_id": "id1",
        "description": "Description for article",
        "author": "publisher of article"
    },
    "id2": {
        "_id": "id2",
        "description": "Description for article",
        "author": "publisher of article"
    },
    "id3": {
        "_id": "id3",
        "description": "Description for article",
        "author": "publisher of article"
    }
}]

是否可以使用MongoDB查询获得此类结果?

1 个答案:

答案 0 :(得分:0)

您可以使用map reduce执行此操作:

  • 地图功能:

    var mapFunction = function() {
        var obj = {};
    
        obj[this._id] = {
    
            "_id": this._id,
            "description": this.description,
            "author": this.author
    
        };
        emit(1,obj);
    };
    
  • 减少功能:

    var reduceFunction = function(key, values) {
    
        var reduced = {};
    
        var output_arr = [];
    
        values.forEach(function(value) {
            Object.keys(value).forEach(function(key) {
                var obj = {};
                obj[key]=value[key];
                output_arr.push(obj);
            });
        });
    
        reduced["data"] = output_arr;
    
        return reduced;
    
    };
    

地图缩减查询:

db.items.mapReduce(mapFunction, reduceFunction, { out: { inline: 1 } })

您可以在results[0].value.data中访问结果。输出是:

{
    "results" : [
        {
            "_id" : 1,
            "value" : {
                "data" : [
                    {
                        "id1" : {
                            "_id" : "id1",
                            "description" : "Description for article",
                            "author" : "publisher of article"
                        }
                    },
                    {
                        "id2" : {
                            "_id" : "id2",
                            "description" : "Description for article",
                            "author" : "publisher of article"
                        }
                    },
                    {
                        "id3" : {
                            "_id" : "id3",
                            "description" : "Description for article",
                            "author" : "publisher of article"
                        }
                    }
                ]
            }
        }
    ],
    "timeMillis" : 11,
    "counts" : {
        "input" : 3,
        "emit" : 3,
        "reduce" : 1,
        "output" : 1
    },
    "ok" : 1
}