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

WBOY
Release: 2024-02-02 14:13:21
forward
842 people have browsed it

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})
Copy after login

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)
}
Copy after login

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)
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!