MongoDB聚合嵌套值

MongoDB聚合嵌套值,mongodb,aggregation-framework,Mongodb,Aggregation Framework,在MongoDB集合中,有嵌套在缺席数组中的数据 { "_id" : ObjectId("5c6c62f3d0e85e6ae3a8c842"), "absence" : [ { "date" : ISODate("2017-05-10T17:00:00.000-07:00"), "code" : "E", "type" : "E", "isPartial" : false }, { "date

在MongoDB集合中,有嵌套在
缺席
数组中的数据

{
"_id" : ObjectId("5c6c62f3d0e85e6ae3a8c842"),
"absence" : [
    {
        "date" : ISODate("2017-05-10T17:00:00.000-07:00"),
        "code" : "E",
        "type" : "E",
        "isPartial" : false
    },
    {
        "date" : ISODate("2018-02-24T16:00:00.000-08:00"),
        "code" : "W",
        "type" : "E",
        "isPartial" : false
    },
    {
        "date" : ISODate("2018-02-23T16:00:00.000-08:00"),
        "code" : "E",
        "type" : "E",
        "isPartial" : false
    },
    {
        "date" : ISODate("2018-02-21T16:00:00.000-08:00"),
        "code" : "U",
        "type" : "U",
        "isPartial" : false
    },
    {
        "date" : ISODate("2018-02-20T16:00:00.000-08:00"),
        "code" : "R",
        "type" : "E",
        "isPartial" : false
    }
]
}
我想通过
缺勤进行聚合。键入
返回每种类型的计数以及
缺勤
子项的总数。结果可能如下所示:

{
    "_id" : ObjectId("5c6c62f3d0e85e6ae3a8c842"),
    "U" : 1,
    "E" : 4,
    "total" : 5
}
这里发布了几个类似的问题,但我还没有成功地修改我的模式的答案。非常感谢您的帮助


另外,是否有GUI建模工具来帮助MongoDB查询构建?从RDBMS查询到Mongo聚合管道的转换非常困难。

您可以使用以下聚合:

db.col.aggregate([
    {  
        $unwind: "$absence" 
    },
    {
        $group: {
            _id: { _id: "$_id", type: "$absence.type" },
            count: { $sum: 1 }
        }
    },
    {
        $group: {
            _id: "$_id._id",
            types: { $push: { k: "$_id.type", v: "$count" } },
            total: { $sum: "$count" }
        }
    },
    {
        $replaceRoot: {
            newRoot: {
                $mergeObjects: [ "$$ROOT", { $arrayToObject: "$types" } ]
            }
        }
    },
    {
        $project: {
            types: 0
        }
    }
])
允许您在每次
缺勤时获取单个文档。然后需要两个,第一个按
类型和
\u id
计数,第二个按
\u id
聚合数据。每个
\u id
都有一个文档,您只需将动态创建的键和值(by)升级到根级别

输出:

{ "_id" : ObjectId("5c6c62f3d0e85e6ae3a8c842"), "total" : 5, "U" : 1, "E" : 4 }

如果您知道“缺席.类型”的所有可能值,那么$根据该值筛选数组并计算筛选数组的$大小。如果您不知道“缺席.类型”中所有可能的值,那么这将不起作用


“差点就成功了,”米克尔说。非常感谢。根级别对象包含我希望在投影中返回的其他字段。我需要做什么来突出这些额外的字段?假设数据中有一个
firstname
字段与缺席数组处于同一级别。谢谢您可以在两个
$group
阶段中添加
firstname:{$first:'firstname'}
db.col.aggregate([

    { $project: { U: { $size: { $filter: { input: "$absence", as: "a", cond: { $eq: [ "$$a.type", "U"]}  }}}, 
                    E: { $size: { $filter: { input: "$absence", as: "a", cond: { $eq: [ "$$a.type", "E"]}  }}} }},
    { $project: { total: { $add: [ "$U", "$E" ]}, U: 1, E: 1}},

])