You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang MongoDB聚合报错:Pipeline阶段规范对象必须仅含一个字段

解决Golang MongoDB聚合查询的"A pipeline stage specification object must contain exactly one field"错误

错误根源在于$match阶段的条件构造错误:你把$gte操作符写成了嵌套的bson.E,导致MongoDB解析时认为一个字段下存在多个子字段,违反了管道阶段的规范要求。

修正后的代码(使用bson.D)

cond := bson.D{
    {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(ctx, mongo.Pipeline{match, group})

更简洁的写法(使用bson.M)

bson.M是map结构,构造查询条件更直观易读:

match := bson.D{{Key: "$match", Value: bson.M{
    "$createTime": bson.M{"$gte": time.Now().AddDate(0, -1, 0)},
}}}
group := bson.D{{Key: "$group", Value: bson.M{
    "_id":   "$name",
    "count": bson.M{"$sum": 1},
}}}
cursor, err := col.Aggregate(ctx, mongo.Pipeline{match, group})

核心修正点:将$createTime的Value从单个bson.E改为包含$gte的bson.D或bson.M,确保每个查询条件的结构符合MongoDB聚合管道的规范。

内容的提问来源于stack exchange,提问作者wate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 14:39:52