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}}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么