使用键值对将mongo数组转换为对象

blu*_*ren 5 mongodb meteor mongodb-query aggregation-framework mongodb-aggregation

我有一个包含一个字符串数组的mongo文档,我需要将这个特定的字符串数组转换为包含键值对的对象数组.以下是我对它的有用的评价.

{
    "_id" : ObjectId("57e3720836e36f63695a2ef2"),
    "platform" : "A1",
    "available" : {
        "Community" : {
            "attributes" : {
                "type" : {
                    "values" : [
                        "well-known",
                        "simple",
                        "complex"
                    ],
                    "defaultValue" : "well-known"
                },
[......]


}
Run Code Online (Sandbox Code Playgroud)

当前查询:

templateAttributes.find({platform:"V1"}).map(function(c){
  //instantiate a new array
  var optionsArray = [];
for (var i=0;i< c['available']['Community']['attributes']['type']['values'].length; i++){
    optionsArray[i] = {};              // creates a new object
    optionsArray[i].label = c['available']['Community']['attributes']['type']['values'][i];
    optionsArray[i].value = c['available']['Community']['attributes']['type']['values'][i];
    }
    return optionsArray;
})[0];
Run Code Online (Sandbox Code Playgroud)

结果:

[{label:"well-known", value:"well-known"},
{label:"simple", value:"simple"},
{label:"complex", value:"complex"}]
Run Code Online (Sandbox Code Playgroud)

我的方法是否足够有效,或者有没有办法优化上述查询以获得相同的预期结果?

chr*_*dam 4

不太确定您想对最终结果做什么,因为键和值是相同的。尽管如此,您可以使用聚合框架,在该框架中,您可以使用将嵌入值数组$unwind展平的运算符对其进行非规范化,即它为每个数组条目生成每个文档的副本。

展平值数组后,您可以对$group值应用累积运算符以聚合它们。运算符的最终管道$project会将先前分组的字段整形为所需的格式。

按照这个例子来理解这个概念:

templateAttributes.aggregate([
    { "$match": { "platform": "V1" } },
    { "$unwind": "$available.Community.attributes.type.values" },
    {
        "$group": {
            "_id": "$available.Community.attributes.type.values",
            "value": { "$first": "$available.Community.attributes.type.values" }
        }
    },
    {
        "$project": {
            "_id": 0,
            "label": "$_id",
            "value": 1
        }
    }
])
Run Code Online (Sandbox Code Playgroud)

由于您使用的是 Meteor,meteor addmeteorhacks:aggregate将为 Meteor 添加适当的聚合支持,以便您可以在集合上运行上述聚合管道。