【问题标题】:How to return multiple values using Go Mongo Distinct如何使用 Go Mongo Distinct 返回多个值
【发布时间】:2021-10-07 18:04:01
【问题描述】:

我想从集合中返回值,一个是批次,应该与特定过滤器不同,即 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)

【问题讨论】:

  • db.collection.distinct 返回不同字段值的 array。如果您想要集合中的其他字段,请使用db.collection.aggregate 查询(使用$group 阶段获取字段的不同值,然后您也可以包含其他字段)。
  • 似乎可行,但无法编写代码。你能用代码解释你的想法吗?
  • 这是 MongoDB 手册中的一个示例:$group - Retrieve Distinct Values。并且,请参阅此帖子:stackoverflow.com/questions/37129612/…

标签: mongodb go


【解决方案1】:

在 prasad 评论后,我用这个解决方案解决了我的问题。

    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

【讨论】:

    【解决方案2】:

    我发现了一个类似的问题,

    您必须使用db.collection.aggregate 查询。请阅读 MongoDB 文档

    Check this out

    Check this out

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-24
      • 2016-08-22
      • 1970-01-01
      • 2019-05-21
      相关资源
      最近更新 更多