Home  >  Article  >  Backend Development  >  Golang mongodb aggregation error: pipeline stage specification object must contain only one field

Golang mongodb aggregation error: pipeline stage specification object must contain only one field

WBOY
WBOYforward
2024-02-02 14:13:21858browse

Golang mongodb 聚合错误:管道阶段规范对象必须仅包含一个字段

Question content

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?


Correct answer


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:

  • Always check the error message returned in the err variable
  • You can enable raw database command logging via:
uri := 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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete