E.S.
E.S.

Reputation: 2841

Summing Values From a Document

In MongoDB 4 I am working with a collection that contains a document-of-documents that contains numbers. I want to sum all those numbers.

Query which right now just spits out the full document:

db.metadata.aggregate([  
   {  
      $match:{  
         "download-md5-checksum":"419f21233097c5f7bcd937a2c94b8032"
      }
   },
   {  
      $group:{  
         _id:"$xled.xled-bad-counts",
         count:{  
            $sum:1
         }
      }
   },
   {  
      $project:{  
         "xled.xled-bad-counts":"$_id",
         count:1,
         _id:0
      }
   }
]).pretty()

{
    "count" : 1,
    "xled" : {
        "xled-bad-counts" : {
            "left-engine-accessory-gearbox-count" : 7,
            "left-engine-accessory-gearbox-minimum" : 2,
            "left-engine-accessory-gearbox-maximum" : 2,
            "left-engine-accessory-gearbox-total" : 3
        }
    }
}

I know about the $sum function but I believe it wants to act on an array, however my data is arranged as a document of documents.

How can I use MongoDB shell commands to properly aggregate this and perform a summation? I'd like my output to just be

{count: 453}

Upvotes: 1

Views: 83

Answers (1)

mickl
mickl

Reputation: 49945

You need $objectToArray operator to aggregate the data from "unknown" keys and then you can pass this value to $sum operator as there will be an array of numbers under xled.v. $let is used here to define a temporary variable that can be then passed to $sum function

db.metadata.aggregate([
    {  
        $project:{  
            _id: 0,
            count: {
                $let: {
                    vars: { xled: { $objectToArray: "$xled.xled-bad-counts" } },
                    in: { $sum: "$$xled.v" }
                }
            }
        }
    }
]).pretty()

Output: { "count" : 453 }

Upvotes: 1

Related Questions