登录
首页 >  Golang >  Go问答

多值返回:Go Mongo Distinct的使用方法

来源:stackoverflow

时间:2024-02-14 21:00:17 271浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《多值返回:Go Mongo Distinct的使用方法》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我想从集合中返回值,其中一个是批次,它应该与特定的过滤器不同,即 value="nice",另一个是供应商。我无法获取供应商值?

如何使用 distinct 实现此目的,我必须使用 find() 吗?

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    filter := bson.D{{Key: "batch", Value: ""}}

    values, err := db.Collection("xyzcollection").Distinct(ctx, "batch", filter)
    if err != nil {
        return nil, err
    }

    batch := make([]string, len(values))
    for i, v := range values {
        batch[i] = v.(string)
    }

    fmt.Println(batch)

正确答案


在普拉萨德发表评论后,我已经用这个解决方案解决了我的问题。

type Example struct {}

    var exm []Example
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    pipeline := []bson.M{
        {"$match": bson.M{"status": "Pending"}},
        {"$group": bson.M{"_id": "$batch"}},
    }

    cursor, err := db.Collection("xyzcollection").Aggregate(ctx, pipeline)
    if err != nil {
        return []Example{}, errors.New(fmt.Sprintf("unable to retrive data: %s ", err.Error()))
    }

    var result Example
    for cursor.Next(ctx) {
        cursor.Decode(&result)
        exm = append(exm, result)
    }
    return exm, nil

今天关于《多值返回:Go Mongo Distinct的使用方法》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>