展开Mongo文档并汇总字段

时间:2018-08-11 00:59:36

标签: mongodb mongodb-query aggregation-framework nosql-aggregation

我有一个具有以下结构的文档

{
"_id" : ObjectId("7f68aab74df07a00a528a02b"),
"T" : ISODate("2018-04-29T00:00:00Z"),
"MP" : [
    1
],
"P" : 123,
"PB" : 234,
"CG" : 3,
"d" : [
    {
        "PS" : 432,
        "PL" : 765,
        "D" : 64,
        "TN302" : NumberLong(41097)
    },
    {
        "PS" : 756,
        "PL" : 345,
        "D" : 563,
        "TN302" : NumberLong(872097)
    },
    {
        "PS" : 345,
        "PL" : 764,
        "D" : 16,
        "TN302" : NumberLong(73597)
    },
    {
        "PS" : 345,
        "PL" : 765,
        "D" : 16,
        "TN302" : NumberLong(26097)
    },
    {
        "PS" : 345,
        "PL" : 787,
        "D" : 2,
        "TN302" : NumberLong(83097)
    },
    {
        "PS" : 267,
        "PL" : 783,
        "D" : 16,
        "TN302" : NumberLong(56097)
    },
    {
        "PS" : 383,
        "PL" : 547,
        "D" : 16,
        "TN302" : NumberLong(33457)
    }
],
"bn" : NumberLong(32097)
}

我想查找特定日期集合文档中所有“ TN302”的总和。

我知道我必须放松对“ d”的理解,但是我不确定如何从那里总结。

我有一个查询,但它返回了“ TN302”具有的所有不同值

db.collection.aggregate(
[{$match: 
{T:ISODate("2018-04-29T00:00:00Z")}}, 
{$unwind: "$d"}, 
{$group: {_id: "$d.TN302", count: 
{$sum: 1}}}]).pretty()

结果

{ "_id" : NumberLong(2506), "count" : 1 }
{ "_id" : NumberLong(1663), "count" : 1 }
{ "_id" : NumberLong(1782), "count" : 1 }
{ "_id" : NumberLong(745), "count" : 1 }
{ "_id" : NumberLong(422), "count" : 1 }
{ "_id" : NumberLong(1675), "count" : 2 }
{ "_id" : NumberLong(714), "count" : 1 }
{ "_id" : NumberLong(5274), "count" : 1 } 

但是如上所述,我想要一个数字,它们是值的总和。

我该怎么做?

谢谢

0 个答案:

没有答案