How to retrieve _id field in a $group statement, when using multiple fields

38 views
Skip to first unread message

Sérgio SP

unread,
Sep 19, 2016, 3:33:10 PM9/19/16
to mgo-users
Hi,

I'm doing an aggregation using a simple Pipe, with a $match, $projet, $sort and $group statements.

I have no problem with the Pipe itself, since the aggregation is working perfectly well.

In the $group step, however, I have some issues. If I write something like this, everything is working  fine:
group := bson.M{"$group": bson.M{"_id": "$product",
"quantity":      bson.M{"$sum": 1},
"totalamount":   bson.M{"$sum": "$netvalue"},
"averageamount": bson.M{"$avg": "$netvalue"}}}

What I need, however, is something like this:
group := bson.M{"$group": bson.M{"_id": bson.M{"month": "$created_month", "product": "$product"},
"quantity":      bson.M{"$sum": 1},
"totalamount":   bson.M{"$sum": "$netvalue"},
"averageamount": bson.M{"$avg": "$netvalue"}}}

When I use this approach, I can't retrieve the values on to the result data struct:

type StatisticByProduct struct {
month   string
product string
}

type Statistic struct {
Key           StatisticByProduct `bson:"_id"`
Quantity      int
TotalAmount   int
AverageAmount float64
}
The call:
var statistics []*Statistic
pipe := c.Pipe([]bson.M{match, project, sort, group})
err = pipe.All(&statistics)

Does not parse "Key"  data, although I can see the data using the following debug code:
var result []bson.D 
err = pipe.All(&result)
log.Printf("%v\n", result[0])
>>> [{_id [{month 2016-09} {product secure}]} {averageamount 12500.309076682317} {quantity 2556} {totalamount 31950790}]

Is there any way to define my structs in a way that the data will be correctly parsed?

Important to remember that when use single key _id in $group statement, everything works fine.

I attached a go source file with my function, with the complete pipeline code.

cheers!

. 
forum.go

Jesse Hallam

unread,
Dec 19, 2016, 10:34:20 AM12/19/16
to mgo-users
I ran into this same problem, and realized my mistake courtesy of http://stackoverflow.com/questions/34479595/go-nested-object-with-mgo-adapter and the comment:

You have to export the fields (capitalize them) to be able to marshal data. Use struct tags to map Mongo column names to Go field names.

You'll want to modify your StatisticByProduct to make the fields public by renaming them to Month and Product and annotating with `bson:"month"` and `bson:"product"` respectively.
Reply all
Reply to author
Forward
0 new messages