Ricardo Moreira
Ricardo Moreira

Reputation: 43

mongo-go-driver aggregate call always returns error

I'm trying to do an aggregation with mongo-go-driver (MongoDB team driver for Golang) and I can't see what I'm doing wrong here:

// 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'"

This is a mongodb error but if I execute this query in a mongodb native client I get the results and no error occurs.

Upvotes: 3

Views: 3457

Answers (2)

Wan B.
Wan B.

Reputation: 18835

An alternative to parsing a string of MongoDB Extended JSON to build an aggregation pipeline, you could also construct a bson.Array object (typed):

For example:

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)

The above snippet is compatible with the current mongo-go-driver version 0.0.12

Upvotes: 1

Ricardo Moreira
Ricardo Moreira

Reputation: 43

I got it!

Two mistakes I was making:

1 - I have to parse an array of JSON objects

2 - No new lines before closing "`"

Here is the working example:

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

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

Upvotes: 1

Related Questions