问题内容
我想获取过去一个月内按名称分组的计数。当我尝试在 golang mongo 客户端中运行以下查询时。我收到错误:
error: 管道阶段规范对象必须仅包含一个字段。
cond := &bson.D{ bson.E{Key: "$createTime", Value: bson.E{Key: "$gte", Value: time.Now().AddDate(0, -1, 0)}}, } match := bson.D{{Key: "$match", Value: cond}} group := bson.D{{Key: "$group", Value: bson.D{ {Key: "_id", Value: "$name"}, {Key: "count", Value: bson.D{{Key: "$sum", Value: 1}}}, }}} cursor, err := col.Aggregate(ctx, mongo.Pipeline{match, group})
登录后复制
我不知道该怎么办?
正确答案
通过进行以下调整,我能够获得所需的结果:
立即学习“go语言免费学习笔记(深入)”;
$createTime 更改为 createTime,我假设您的字段名称不以 $ 开头bson.E{Key: “$gte”, Value: time.Now().AddDate(0, -1, 0)} 更改为 bson.D{{Key: “$gte”, Value: time .Now().AddDate(0, -1, 0)}}
cond := &bson.D{ bson.E{Key: "createTime", Value: bson.D{{Key: "$gte", Value: time.Now().AddDate(0, -1, 0)}}},}match := bson.D{{Key: "$match", Value: cond}}group := bson.D{{Key: "$group", Value: bson.D{ {Key: "_id", Value: "$name"}, {Key: "count", Value: bson.D{{Key: "$sum", Value: 1}}},}}}cursor, err := col.Aggregate(context.TODO(), mongo.Pipeline{match, group})if err != nil { log.Println("Error: ", err)}
登录后复制
调试此类问题的一些技巧:
始终检查 err 变量中返回的错误消息您可以通过以下方式启用原始数据库命令日志记录:
uri := options.Client().ApplyURI(appSettings.MongoDbUri)if appSettings.LogDatabaseCommands { cmdMonitor := &event.CommandMonitor{ Started: func(_ context.Context, evt *event.CommandStartedEvent) { log.Print(evt.Command) }, } uri.SetMonitor(cmdMonitor)}
登录后复制
以上就是Golang mongodb 聚合错误:管道阶段规范对象必须仅包含一个字段的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2485852.html