将两个MongoDB聚合合并到一个管道中

时间:2015-04-26 10:12:38

标签: node.js mongodb

我有人口普查的集合,我仍然没有主导“聚合”功能,只用一个查询来获得结果。

该集合具有this format(加上ISO 8601时间戳)。这样,每次进行人口普查时,我们都可以注册当前的年龄和计数(可以添加/修改/删除以前的年龄)。

现在我有两个“聚合”查询to return this

  1. Get the AVG, MAX, MIN of all the registries in the DB.
  2. Get each age and show a total (“sum”) of people with that age.
  3. 但是我需要通过一个“聚合”查询获得这些结果,但管道对我来说有点困难,我无法获得统计数据然后“解除”人口以获得总和......

    有关如何合并这两个查询的任何帮助吗?提前谢谢大家!

1 个答案:

答案 0 :(得分:2)

尝试以下聚合管道,它应该给出两个查询的结果:

db.collection('population').aggregate([
    {
        "$unwind": "$population"
    },
    {
        "$group": {
            "_id": 0,
            "doc": {
                "$push": "$$ROOT"
            },
            "average_age": {
                "$avg": "$population.age"
            },
            "max_age": {
                "$max": "$population.age"
            },
            "min_age": {
                "$min": "$population.age"
            },
            "average_population": {
                "$avg": "$population.count"
            },
            "max_population": {
                "$max": "$population.count"
            },
            "min_population": {
                "$min": "$population.count"
            }
        }
    },
    {
        "$unwind": "$doc"
    },
    {
        "$group": {
            "_id": "$doc.population.age",
            "sum": { "$sum": "$doc.population.count" },
            "average_age": { "$first": "$average_age"},
            "max_age": { "$first": "$max_age"},
            "min_age": { "$first": "$min_age"},
            "average_population": { "$first": "$average_population"},
            "max_population": { "$first": "$max_population"},
            "min_population": { "$first": "$min_population"}
        }
    }
])