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

mongo-go-driver aggregate call always returns error

我正在尝试使用 mongo-go-driver(MongoDB Golang 的团队驱动程序)进行聚合,但我看不出我在这里做错了什么:

// group
group, 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 本机客户端中执行此查询,我会得到结果并且不会发生错误。

我明白了!

我犯了两个错误:

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

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

这是工作示例:

    group, e := bson.ParseExtJSONArray(`[{
      "$group": {
        "_id":{
          "ProductCode":"$ProductCode",
          "Dir":"$Dir",
          "WharehouseID":"$WharehouseID"
        }
      }
    }]`)

    cursor, e := myCollection.Aggregate(
       context.Background(),
       group,
    )

解析 MongoDB Extended JSON to build an aggregation pipeline, you could also construct a 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 version 0.0.12

兼容