Home > Article > Backend Development > Golang mongodb aggregation error: pipeline stage specification object must contain only one field
I want to get the count grouped by name within the past month. When I try to run the following query in golang mongo client. I get the error:
error:
The pipeline stage specification object must contain only one field.
cond := &bson.D{ bson.E{Key: "$createTime", Value: bson.E{Key: "$gte", Value: time.Now().AddDate(0, -1, 0)}}, } match := bson.D{{Key: "$match", Value: cond}} group := bson.D{{Key: "$group", Value: bson.D{ {Key: "_id", Value: "$name"}, {Key: "count", Value: bson.D{{Key: "$sum", Value: 1}}}, }}} cursor, err := col.Aggregate(ctx, mongo.Pipeline{match, group})
I do not know what to do?
I was able to get the desired results by making the following adjustments:
$createTime
changed to createTime
, I assume your field name does not start with $
bson.E{Key: "$gte", Value: time.Now().AddDate(0, -1, 0)}
Change to bson.D{{Key: "$gte", Value: time .Now().AddDate(0, -1, 0)}}
cond := &bson.D{ bson.E{Key: "createTime", Value: bson.D{{Key: "$gte", Value: time.Now().AddDate(0, -1, 0)}}}, } match := bson.D{{Key: "$match", Value: cond}} group := bson.D{{Key: "$group", Value: bson.D{ {Key: "_id", Value: "$name"}, {Key: "count", Value: bson.D{{Key: "$sum", Value: 1}}}, }}} cursor, err := col.Aggregate(context.TODO(), mongo.Pipeline{match, group}) if err != nil { log.Println("Error: ", err) }
Some tips for debugging this type of problem:
err
variableuri := options.Client().ApplyURI(appSettings.MongoDbUri) if appSettings.LogDatabaseCommands { cmdMonitor := &event.CommandMonitor{ Started: func(_ context.Context, evt *event.CommandStartedEvent) { log.Print(evt.Command) }, } uri.SetMonitor(cmdMonitor) }
The above is the detailed content of Golang mongodb aggregation error: pipeline stage specification object must contain only one field. For more information, please follow other related articles on the PHP Chinese website!