如何使用Go Mongo的Distinct方法返回多个字段值
结论
Distinct() 方法仅支持返回单个指定字段的去重结果,无法同时获取 vendor 字段的值,你的需求无法仅通过该方法实现,需使用 Find() 或聚合框架 Aggregate() 实现。
现有代码问题修正
你当前的过滤条件写的是匹配 batch 为空字符串,需要先调整为你要求的 value="Nice" 条件:
filter := bson.D{{Key: "value", Value: "Nice"}}
实现方案
这里提供只查询一次数据库的实现方案,性能更高:
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() filter := bson.D{{Key: "value", Value: "Nice"}} // 仅查询需要的batch和vendor字段,减少无效数据传输 cursor, err := db.Collection("xyzcollection").Find(ctx, filter, options.Find().SetProjection(bson.D{ {Key: "batch", Value: 1}, {Key: "vendor", Value: 1}, {Key: "_id", Value: 0}, })) if err != nil { return nil, err } defer cursor.Close(ctx) type resultItem struct { Batch string `bson:"batch"` Vendor string `bson:"vendor"` } var items []resultItem if err = cursor.All(ctx, &items); err != nil { return nil, err } // 本地做batch去重,同时收集vendor batchSet := make(map[string]struct{}) var batches []string var vendors []string for _, item := range items { // 去重添加batch if _, ok := batchSet[item.Batch]; !ok { batchSet[item.Batch] = struct{}{} batches = append(batches, item.Batch) } // 添加vendor,如果需要vendor也去重,可以和batch一样用set处理 vendors = append(vendors, item.Vendor) } fmt.Println("去重后的batch列表:", batches) fmt.Println("vendor列表:", vendors)
如果你的需求是按batch分组获取每个batch对应的关联vendor,直接用聚合框架更合适:
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() pipeline := mongo.Pipeline{ bson.D{{Key: "$match", Value: bson.D{{Key: "value", Value: "Nice"}}}}, bson.D{{Key: "$group", Value: bson.D{ {Key: "_id", Value: "$batch"}, {Key: "vendors", Value: bson.D{{Key: "$addToSet", Value: "$vendor"}}}, }}}, } cursor, err := db.Collection("xyzcollection").Aggregate(ctx, pipeline) if err != nil { return nil, err } defer cursor.Close(ctx) var groupRes []bson.M if err = cursor.All(ctx, &groupRes); err != nil { return nil, err } var batches []string for _, res := range groupRes { batches = append(batches, res["_id"].(string)) // res["vendors"]就是当前batch对应的去重vendor列表 }
内容的提问来源于stack exchange,提问作者Zayn
相关产品推荐
相关产品推荐

