首页  >  文章  >  后端开发  >  Golang mongodb 聚合错误:管道阶段规范对象必须仅包含一个字段

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

WBOY
WBOY转载
2024-02-02 14:13:21815浏览

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)
}

以上是Golang mongodb 聚合错误:管道阶段规范对象必须仅包含一个字段的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除