更改名称聚合字段mongodb

时间:2018-07-26 12:12:51

标签: mongodb mongoose

我正在MongoDB中进行聚合,我想更改参考字段的名称:

这是我的汇总:

[

    {"$ match": {
    "attrName": {$ in: arr}}},
    {"$ group": {
        "_id": {
            "recvTime": "$ recvTime",
            "attrName": "$ attrName",
            "attrValue": "$ attrValue"
        }
    }},
    {"$ group": {
        "_id": "$ _id.attrName",
        "dates": {
            "$ push": {
                "recvTime": "$ _id.recvTime",
                "attrValue": "$ _id.attrValue"

            },
        },
    }}
    ]

这是您的答案:

[
    {
        "_id": "var_ContadorRiego",
        "dates": [
            {
                "recvTime": "2018-03-24T01: 18: 18.619Z",
                "attrValue": "12"
            },
            {
                "recvTime": "2018-03-25T01: 18: 18.619Z",
                "attrValue": "19"
            }
        ]
    },
    {
        "_id": "var_TempExt",
        "dates": [
            {
                "recvTime": "2018-03-25T01: 18: 18.619Z",
                "attrValue": "16.511116"
            },
            {
                "recvTime": "2018-03-24T01: 18: 18.619Z",
                "attrValue": "12.511116"
            }
        ]
    }
]

我想在_id put name,recvTime put name和attrValue put value的位置输入

最终目标如下:

[
     {
         "name": "var_ContadorRiego",
         "dates": [
             {
                 "name": "2018-03-24T01: 18: 18.619Z",
                 "value": "12"
             },
             {
                 "name": "2018-03-25T01: 18: 18.619Z",
                 "value": "19"
             }
         ]
     },
     {
         "name": "var_TempExt",
         "dates": [
             {
                 "name": "2018-03-25T01: 18: 18.619Z",
                 "value": "16.511116"
             },
             {
                 "name": "2018-03-24T01: 18: 18.619Z",
                 "value": "12.511116"
             }
         ]
     }
]

这可以直接从聚合中完成吗?还是我必须遍历整个对象并进行更改?

问候,谢谢。

1 个答案:

答案 0 :(得分:0)

首先通过以下方式更改第二个 $ group

{"$group": {
    "_id": "$_id.attrName",
    "dates": {
        "$ push": {
            "time": "$_id.recvTime",
            "name": "$_id.attrName",
            "value": "$ _id.attrValue"
        },
    },
}} 

然后在聚合管道的末尾使用 $ project 重命名_id字段。

{ $project: {  
      _id: 0,
      name: "$_id",
   }
}

我希望这对您有用。