Joe Taras
Joe Taras

Reputation: 15399

Aggregation on multi field

Reading MongoDb documentation about aggregation operation, I've found this:

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

)

But, suppose I have another field named phone, how can I aggregate about cust_id and phone?

I've tried as follow:

{ $group: { _id: {"$cust_id", "$phone"}, total: { $sum: "$amount" } } },

But doesn't work

EDIT

I want this behaviour:

SELECT SUM(amount)
FROM orders
GROUP BY cust_id, phone

But I have this error (I must attach screenshot because by MongoChef I can't textual error):

enter image description here

Upvotes: 0

Views: 55

Answers (1)

Alex Blex
Alex Blex

Reputation: 37108

There is nothing to explain. It's just wrong syntax. Objects should have field names, not only field values. E.g.:

{ $group: { _id: {id:"$cust_id", phone:"$phone"}, total: { $sum: "$amount" } } },

Upvotes: 2

Related Questions