dongzhan8620 2016-04-26 20:25
浏览 12
已采纳

选择功能不起作用只获得我想要的数组

i have a document like this

{
"_id": {
    "$oid": "570bc73da8ebd9005dd54de3"
},
"title": "dota",
"imgurl": "asd.com",
"description": "",
"hints": [
    {
        "date": "2016-04-26 22:50:12.6069011 +0430 IRDT",
        "description": "narinin"
    },
    {
        "date": "2016-04-26 22:50:12.6069011 +0430 IRDT",
        "description": "doros shod"
    }
]
}

the script i execute is

hints := hints{}
err := db.C("games").Find(bson.M{"title": game}).Select(bson.M{"hints": 0}).One(&hints)

my 2 structs are

type Game struct {
Id          bson.ObjectId `bson:"_id,omitempty"`
Title       string        `json:"title"`
Imgurl      string        `json:"imgurl"`
Description string        `json:"desc"`
Hints       []*hint       `bson:"hints", json:"hints"`
}

type hint struct {
    Description string    `json:"desc"`
    Date        time.Time `json:"date"`
}

when i use the script all i get is a none sense date string witch is not even in document how can i get just the slice of hints from a game

  • 写回答

1条回答 默认 最新

  • drot98385 2016-04-27 00:44
    关注

    You have too keep using Game struct to receive the result, even for only hints column. Also your select query should be .Select(bson.M{"hints": 1}).

    I fixed your code, and tried in my local, this one is working.

    game := Game{}
    err = db.C("games").Find(bson.M{"title": "dota"})
            .Select(bson.M{"hints": 1}).One(&game)
    if err != nil {
        panic(err)
    }
    
    for _, hint := range game.Hints {
        fmt.Printf("%#v
    ", *hint)
    }
    

    All properties of game is empty, except Hints.

    EDITED 1

    To get the first 10 rows on hints, the easiest way would be by playing the slice, but this is bad because it need to fetch all the rows first.

    for _, hint := range game.Hints[:10] { // 10 rows
        fmt.Printf("%#v
    ", *hint)
    }
    

    The other solution (which is better), is by using $slice on the .Select() query.

    selector := bson.M{"hints": bson.M{"$slice": 10}} // 10 rows
    
    err = db.C("so").Find(bson.M{"title": "dota"})
            .Select(selector).One(&game)
    

    EDITED 2

    Use []int{skip, limit} on the $slice, to support skip and limit.

    selector := bson.M{"hints": bson.M{"$slice": []int{0, 10}}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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