I have a collection in mongo on which I run the following query
db.feeds.aggregate({"$match":{createdat:"20190203"}}, {"$group": {_id: {"type": "$type"}, total: {$sum: 1} }},{"$project": {"type": "$_id.type", "tot": "$total", "_id": 0} } )
It works as expected and returns,
{ "type" : "f", "tot" : 1 }
{ "type" : "ebm", "tot" : 1 }
{ "type" : "b", "tot" : 3 }
However, when I try replicating the pipeline in Golang, as follow:
pipeline := []bson.M{
// match
{"$match": bson.M{"createdat": when}},
// group
{"$group": bson.M{
"_id": bson.M{"type": "$type"}, // "$fieldname" - return the field
"TotalFeeds": bson.M{"$sum": 1}}},
// project
{"$project": bson.M{"type": "$_id.type", // project selects subset of fields
"TotalFeeds": "$TotalFeeds", // rename fiedls
"_id": 0}}, // 0 means not show _id
}
The returned count is 0.
map[$match:map[createdat:20190203]] map[$group:map[TotalFeeds:map[$sum:1] _id:map[type:$type]]] map[$project:map[type:$_id.type TotalFeeds:$TotalFeeds _id:0]]]
{f 0 }
{ebm 0 }
{b 0 }
[{f 0 } {ebm 0 } {b 0 }]
Below the entire function I am using in Golang:
func CountFeeds(when string) Feeds {
ctx, _ := context.WithTimeout(context.Background(), 60*time.Second)
pipeline := []bson.M{
// match
{"$match": bson.M{"createdat": when}},
// group
{"$group": bson.M{
"_id": bson.M{"type": "$type"}, // "$fieldname" - return the field
"TotalFeeds": bson.M{"$sum": 1}}},
// project
{"$project": bson.M{"type": "$_id.type", // project select subset of fields
"TotalFeeds": "$TotalFeeds", // rename fiedls
"_id": 0}}, // 0 means not show _id
}
fmt.Println(pipeline)
curs, err := db.Collection("feeds").Aggregate(ctx, pipeline)
utilities.Catch(err)
defer curs.Close(ctx)
element := Feeds{}
e := []Feeds{}
for curs.Next(ctx) {
err := curs.Decode(&element)
fmt.Println(element)
utilities.Catch(err)
e = append(e, element)
}
fmt.Println(e)
return element
}