为了账号安全,请及时绑定邮箱和手机立即绑定

mongo-go-driver 聚合调用总是返回错误

mongo-go-driver 聚合调用总是返回错误

Go
富国沪深 2023-03-21 17:20:13
我正在尝试使用 mongo-go-driver(Golang 的 MongoDB 团队驱动程序)进行聚合,但我看不出我在这里做错了什么:// groupgroup, e := bson.ParseExtJSONObject(`    {      "$group": {        "_id":{          "ProductCode":"$ProductCode",          "Dir":"$Dir",          "WharehouseID":"$WharehouseID"        }      }    }`)cursor, e := myCollection.Aggregate(    context.Background(),    group,)// e output: "(Location40324) Unrecognized pipeline stage name: '_id'"这是一个 mongodb 错误,但如果我在 mongodb 本机客户端中执行此查询,我会得到结果并且不会发生错误。
查看完整描述

2 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

除了解析一串MongoDB 扩展 JSON来构建聚合管道之外,您还可以构建一个bson.Array对象(类型化):

例如:

pipeline := bson.NewArray(

    bson.VC.DocumentFromElements(

        bson.EC.SubDocumentFromElements(

            "$group",

            bson.EC.SubDocumentFromElements(

                "_id",

                bson.EC.String("ProductCode","$ProductCode"),

                bson.EC.String("Dir","$Dir"),

                bson.EC.String("WharehouseID","$WharehouseID"),

            ),

        ),

    ),

)

cursor, err := collection.Aggregate(context.Background(), pipeline)

上面的代码片段与当前的mongo-go-driver 版本 0.0.12兼容



查看完整回答
反对 回复 2023-03-21
?
慕标琳琳

TA贡献1830条经验 获得超9个赞

我得到了它!

我犯了两个错误:

1 - 我必须解析一个 JSON 对象数组

2 - 关闭“`”之前没有换行

这是工作示例:

    group, e := bson.ParseExtJSONArray(`[{

      "$group": {

        "_id":{

          "ProductCode":"$ProductCode",

          "Dir":"$Dir",

          "WharehouseID":"$WharehouseID"

        }

      }

    }]`)


    cursor, e := myCollection.Aggregate(

       context.Background(),

       group,

    )


查看完整回答
反对 回复 2023-03-21
  • 2 回答
  • 0 关注
  • 241 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号