dongyilai4214 2018-04-13 07:41
浏览 62

mgo.v2,$ sample始终返回1条相同的记录

I need get 1 rand record from a collection. I check it on robo-mongo and it work great. But in golang project using mgo.v2, It always return the same record all the time . Is there any bug with the library, or I misunderstanding?

I use "gopkg.in/mgo.v2". Here is my code:

var err error

    pipe := col.Pipe([]bson.M{
        {"$match": bson.M{ "ad_group_id": worker.creative.AdGroupId }},
        {"$sample": bson.M{ "size": 1 }},
    })
    var resp []model.Coordinate
    err = pipe.All(&resp)

log.Print("++++++++++++++++++++++++++++++++++++++++++++++++++: ",resp)

=>

[
    {
        ObjectIdHex("...") ObjectIdHex("...") ObjectIdHex("...") 
        {
            Point [33 33]
        } 
        t3
    }
]

Coordinate collections: enter image description here

  • 写回答

1条回答 默认 最新

  • dtt2012 2018-04-13 08:52
    关注

    Your use of the mgo package is invalid. If you use Pipeline.One(), you should pass a target of a single model.Coordinate or *model.Coordinate:

    var resp model.Coordinate
    err = pipe.One(&resp)
    

    Otherwise you get an error like:

    Unsupported document type for unmarshalling: []model.Coordinate
    

    If you're going to get a single result, then of course there is no need to specify a size > 1 in the pipeline, so simply use:

    {"$sample": bson.M{"size": 1}},
    

    If you want to get multiple random results, then you may use a slice and Pipeline.All() like in this example:

    pipe := col.Pipe([]bson.M{
        {"$match": bson.M{"ad_group_id": worker.creative.AdGroupId}},
        {"$sample": bson.M{"size": 2}},
    })
    var resp []model.Coordinate
    err = pipe.All(&resp)
    
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法