dongyong2063 2019-05-11 20:11
浏览 14
已采纳

如何获得收藏品的独特价值

I am trying the use of mongodb and Go and I cannot get the distinct values of the field in a collection.

This is my code:

import (
    "context"
    "fmt"
    "log"
    "time"

    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)


type House struct {
    Ciudad string
}


func main() {

    client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
    if err != nil {
        log.Fatal(err)
    }
    ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
    err = client.Connect(ctx)

    collection := client.Database("test").Collection("houses")

    var house repository.House

    fmt.Println(collection.Distinct(ctx, "City", &house))

}

After execute this always I am geting an empty array. Any idea that is wrong in this code?

  • 写回答

1条回答 默认 最新

  • douluan5523 2019-05-12 17:03
    关注

    Replace the line

    fmt.Println(collection.Distinct(ctx, "City", &house))
    

    With

    fmt.Println(collection.Distinct(ctx, "City", bson.D{{}}))
    

    The third parameter, filter, is a BSON document, https://godoc.org/go.mongodb.org/mongo-driver/mongo#Collection.Distinct. Note that Distinct() returns two values, ([]interface, error).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥20 笔记本电脑 处理器是AMD的r7
  • ¥15 100 内验证哥德巴赫巴赫猜想
  • ¥15 clash节点timeout
  • ¥15 需要在vitis下实现彩调视频图像累加,并输出
  • ¥15 解决不了的LNK2019错误
  • ¥20 MATLAB仿真三相桥式全控整流电路
  • ¥15 EDA技术关于时序电路设计
  • ¥15 百度文心一言流式返回sse失败
  • ¥15 由于远程方已关闭传输流,身份验证失败