欢迎光临
我们一直在努力

Golang mongodb 聚合错误:管道阶段规范对象必须仅包含一个字段

golang mongodb 聚合错误:管道阶段规范对象必须仅包含一个字段

问题内容

我想获取过去一个月内按名称分组的计数。当我尝试在 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})

我不知道该怎么办?

正确答案

通过进行以下调整,我能够获得所需的结果:

  • $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)
}
赞(0) 打赏
未经允许不得转载:码农资源网 » Golang mongodb 聚合错误:管道阶段规范对象必须仅包含一个字段
分享到

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册