MongoDb中的文档明智摘要

时间:2018-03-21 13:19:22

标签: mongodb mongodb-query

我的应用程序中有一个cron,它以下列格式存储应用程序数据。每天一份文件。以下是一天的一份样本文件。

{
    timestamp: "2018-02-01",
    data: [
        {
            project_name: "ABC",
            engineer: "tom"
            line_of_code: 100,
            testcases: 10
        },
        {
            project_name: "DEF",
            engineer: "tom",
            line_of_code: 300,
            testcases: 3
        },
        {
            project_name: "DEF",
            engineer: "dick",
            line_of_code: 100,
            testcases: 10
        },
        {
            project_name: "GHI",
            engineer: "dick",
            line_of_code: 10,
            testcases: 10
        },
        {
            project_name: "JKL",
            engineer: "harry",
            line_of_code: 110,
            testcases: 14
        }
    ]
}

我需要绘制一些情节,我需要以下列方式进行每日总结。

[
    {
        timestamp: "2018-03-01",
        "tom": {
            "total_line_of_code": XXXX,
            "total_testcases": YYYY
        },
        "dick": {
            "total_line_of_code": XXXX,
            "total_testcases": YYYY
        },
        "harry": {
            "total_line_of_code": XXXX,
            "total_testcases": YYYY
        }
    },
    {
        timestamp: "2018-03-02",
        "tom": {
            "total_line_of_code": XXXX,
            "total_testcases": YYYY
        },
        "dick": {
            "total_line_of_code": XXXX,
            "total_testcases": YYYY
        },
        "harry": {
            "total_line_of_code": XXXX,
            "total_testcases": YYYY
        }
    }
]

是否可以在mongodb中编写一个类似的查询,它可以每天合并并返回一个数组,其中每个对象代表一天的摘要。

1 个答案:

答案 0 :(得分:1)

您可以使用以下聚合:

db.col.aggregate([
    {
        $unwind: "$data"
    },
    {
        $group: {
            _id: {
                timestamp: "$timestamp",
                engineer: "$data.engineer"
            },
            lines_of_code: { $sum: "$data.line_of_code" },
            testcases: { $sum: "$data.testcases" }
        }
    },
    {
        $group: {
            _id: "$_id.timestamp",
            items: {
                $push: {
                    k: "$_id.engineer",
                    v: {
                         total_line_of_code: "$lines_of_code",
                         total_testcases: "$testcases"
                    }
                }
            }
        }
    },
    {
        $project: {
            _id: 0,
            timestamp: "$_id",
            data: {
                $arrayToObject: "$items"
            }
        }
    },
    {
        $replaceRoot: {
            newRoot: {
                $mergeObjects: [ "$$ROOT", "$data" ]
            }
        }
    },
    {
        $project: {
            data: 0
        }
    }
])

要将文档转换为engineer字段用作关键字的格式,您需要使用$arrayToObject - 这就是我们转换为属性v和{{1}的原因}。在此之前,您需要使用k,然后每天按人分组以获取总数。