在 MongoDB 中,使用聚合管道聚合数据时,Go 语言程序中的结果与命令行界面 (CLI) 中的结果不一致。管道在 CLI 中按预期工作,但 Go 语言程序返回的计数为 0。问题在于管道定义中使用了错误的类型(bson.M{} 而不是 bson.D{}),并且 feeds{} 结构与投影阶段定义不匹配。
我在 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
}解决方案
首先,使用 bson.D{} 而不是 bson.M{}。这是因为 bson.d{} 应该在顺序很重要的情况下使用,例如 mongodb 命令。
您还可以将整个管道封装在mongo.Pipeline中。例如:
pipeline := mongo.pipeline{
{{"$match", bson.d{{"createdata", 10}}}},
{{"$group", bson.d{
{"_id", bson.d{{"type", "$type"}}},
{"totalfeeds", bson.d{{"$sum", 1}}},
}}},
{{"$project", bson.d{
{"type", "$_id.type"},
{"totalfeeds", "$totalfeeds"},
{"_id", 0}},
}},
}
检查您的 feeds{} 结构映射。确保指定 bson 映射,即:
type feeds struct {
type string `bson:"type"`
totalfeeds int `bson:"totalfeeds"`
}
或者,在投影阶段 $project 中,您对字段使用一致的大小写。例如,指定全部小写 type 和 totalfeeds 或全部大写 type 和 totalfeeds。
pipeline := mongo.pipeline{
{{"$match", bson.d{{"createdata", 10}}}},
{{"$group", bson.d{
{"_id", bson.d{{"type", "$type"}}},
{"totalfeeds", bson.d{{"$sum", 1}}},
}}},
{{"$project", bson.d{
{"type", "$_id.type"},
{"totalfeeds", "$totalfeeds"},
{"_id", 0}},
}},
}
那么您不必在结构中指定 bson 映射:
type MyStruct struct {
Type string
Total int
}
因此,要么在结构中使用一致的字段名称大小写,要么显式提供 bson 映射。
到这里,我们也就讲完了《CLI 与聚合管道相比呈现错误的数据》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
