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
相关产品推荐
相关产品推荐

