Search code examples
mongodbgomongo-go

Why mongo-go-driver aggregation result object keys returned as "Key"


I want to group some data with mongo-go-driver using aggregate, but the json result confused me, because the row key replaced with "Key" and and the real key become the "Key"s value

var result primitive.A
pipeline := mongo.Pipeline{{{"$group", bson.D{{"_id", "$nis"}}}}}
cursor, err := db.NilaiUH.Aggregate(context.TODO(), pipeline)
cursor.All(context.Background(), &result)
json.NewEncoder(w).Encode(&result)

Here is the result

[
  [
    {
      "Key": "_id",
      "Value": 15100
    }
  ],
  [
    {
      "Key": "_id",
      "Value": 15101
    }
  ]
]

Solution

  • The new version of MongoDB driver treated the empty interface as an array of keys and values instead of a mapping between strings and empty interfaces. I have corrected the issue use the following code:

    // register custom codec registry to handle empty interfaces
    rb := bson.NewRegistryBuilder()
    rb.RegisterTypeMapEntry(bsontype.EmbeddedDocument, reflect.TypeOf(bson.M{}))
    
    client, err := mongo.NewClient(options.Client().ApplyURI(url).SetRegistry(rb.Build()))