
我想获取过去一个月内按名称分组的计数。当我尝试在 golang mongo 客户端中运行以下查询时。我收到错误:
error: 管道阶段规范对象必须仅包含一个字段。
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})我不知道该怎么办?
通过进行以下调整,我能够获得所需的结果:
立即学习“go语言免费学习笔记(深入)”;
$createTime 更改为 createTime,我假设您的字段名称不以 $ 开头bson.E{Key: "$gte", Value: time.Now().AddDate(0, -1, 0)} 更改为 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)
}调试此类问题的一些技巧:
err 变量中返回的错误消息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)
}以上就是Golang mongodb 聚合错误:管道阶段规范对象必须仅包含一个字段的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号