0

I have a document with the following structure

{
"_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)
}

I want to find the sum of all the "TN302" in the documents of a collection on a particular date.

I know I have to unwind on "d" but I'm not sure how to sum up from there.

I have a query but it returns all of the different values that "TN302" has

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

which results in

{ "_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 } 

However as I mentioned above I want one number which is the sum of the values.

How can I do this?

Thanks

s7vr
  • 73,656
  • 11
  • 106
  • 127
000
  • 99
  • 1
  • 8

0 Answers0