Question

I have a MongoDB collection with documents corresponding to user projects and containing the following relevant elements:

{
  "InstanceId": "Instance1",
  "Username": "JohnSmith",
  "ProjectTotals": 
    {
      Subtotal: 100.00
      TaxTotal: 0.000
    }
}

Each instance contains many users and each user can have many projects.

I am trying to get some aggregate data to allow me to show an instance manager the number of projects each user has created as well as the total cost of all projects and average project cost for each user.

So far, I have built the following query (which ignores the taxes for now):

db.projects.aggregate( 
{$match: 
    {InstanceId: "Instance1", 
     ProjectTotals:{"$exists":true}     }},
{$group:
    {_id: "$Username", 
        count: { $sum: 1 },
        total: { $sum: "ProjectTotals.SubTotal"},
        average: {$avg: "ProjectTotals.SubTotal"}}})

This query successfully gives me the count for each user, but the total and average are 0 for each user:

"result" : [ 
    {
        "_id" : "JohnSmith",
        "count" : 10,
        "total" : 0,
        "average" : 0
    }
]

Without changing my database schema, how can I access ProjectTotals.SubTotal for aggregation functions?

Was it helpful?

Solution

You need $ in front of the ProjectTotals plus you misspelled SubTotal (it's Subtotal in your schema but SubTotal in your aggregation). Making both corrections:

db.projects.aggregate(
                      {$match: {InstanceId: "Instance1", ProjectTotals:{"$exists":true}}},
                      {$group: {_id: "$Username", count: { $sum: 1 },
                           total: {$sum: "$ProjectTotals.Subtotal"}, 
                                    average: {$avg: "$ProjectTotals.Subtotal"}}}
                      )

Running that against your sample data I get:

{ "_id" : "JohnSmith", "count" : 1, "total" : 100, "average" : 100 }

Which is what I would expect from a data sample of 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top