ujjwal-gupta
ujjwal-gupta

Reputation: 123

Nested output from mongo aggregate query

This is right out of the mongo aggregation documentation. Lets say I have these set of documents:

{ _id: 1, cust_id: "abc1", ord_date: ISODate("2012-11-02T17:04:11.102Z"), status: "A", amount: 50 }
{ _id: 2, cust_id: "xyz1", ord_date: ISODate("2013-10-01T17:04:11.102Z"), status: "A", amount: 100 }
{ _id: 3, cust_id: "xyz1", ord_date: ISODate("2013-10-12T17:04:11.102Z"), status: "D", amount: 25 }
{ _id: 4, cust_id: "xyz1", ord_date: ISODate("2013-10-11T17:04:11.102Z"), status: "D", amount: 125 }
{ _id: 5, cust_id: "abc1", ord_date: ISODate("2013-11-12T17:04:11.102Z"), status: "A", amount: 25 }

I can run this aggregate query:

db.orders.aggregate([
                 { $match: { status: "A" } },
                 { $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
                 { $sort: { total: -1 } }
               ])

To get this response:

{ "_id" : "xyz1", "total" : 100 }
{ "_id" : "abc1", "total" : 75 }

But what if a want the response in a nested format? Any way of achieving that without using mapReduce? Something like this:

{ "_id" : "xyz1", "amount": { "total" : 100 } }
{ "_id" : "abc1", "amount": { "total" : 75 } }

Upvotes: 1

Views: 418

Answers (1)

Sede
Sede

Reputation: 61225

You need to project your documents using the $project operator

db.collection.aggregate([
    { "$group": { 
        "_id": "$cust_id", 
        "total": { "$sum": "$amount" }
    }}, 
    { "$project": { "amount.total": "$total" } },
    { "$sort": { "amount.total": -1 } }

])

Which returns:

{ "_id" : "xyz1", "amount" : { "total" : 250 } }
{ "_id" : "abc1", "amount" : { "total" : 75 } }

Upvotes: 1

Related Questions