Golang MongoDB类库使用

35 阅读1分钟

Aggregate、pipeline 报错

go mongodb error (Location40323) A pipeline stage specification object must contain exactly one field.

解决

pipeline := bson.A{  
bson.M{"$match": bson.M{"host": "api-img-xjp.fengkongcloud.com"}},  
bson.M{"$group": bson.M{"_id": "$json.type", "count": bson.M{"$sum": 1}}},  
}

修改为

pipeline := []bson.M{  
{"$match": bson.M{"host": "api-img-xjp.fengkongcloud.com"}},  
{"$group": bson.M{"_id": "$json.type", "count": bson.M{"$sum": 1}}},  
}

db := mgd.Client.Database("test")  
  
cursor, err := db.Collection("x-x-x").Aggregate(ctx, pipeline)