我在 mongo 中有一个集合,我在上面运行以下查询
db.feeds.aggregate({"$match":{createdat:"20190203"}}, {"$group": {_id: {"type": "$type"}, total: {$sum: 1} }},{"$project": {"type": "$_id.type", "tot": "$total", "_id": 0} } )
它按预期工作并返回,
{ "type" : "f", "tot" : 1 }
{ "type" : "ebm", "tot" : 1 }
{ "type" : "b", "tot" : 3 }
但是,当我尝试在 Golang 中复制管道时,如下所示:
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
}
返回的计数为 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 }]
下面是我在 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
}
智慧大石
相关分类