select function doesn't work just get the array I want
CallMeLoki :
I have a file 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 two structures 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 date string that doesn't make sense, not even witch in the docs, how can I get part of the prompt from the game
novalagung:
You also have to keep using Game
struct to receive results, even for hints
columns only. Your select query should also be .Select(bson.M{"hints": 1})
.
I fixed your code and tried this locally.
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\n", *hint)
}
All properties except game
are empty Hints
.
Edit 1
To get the first 10 rows hints
, the easiest way is to play the slice, but that's bad because it needs to get all the rows first.
for _, hint := range game.Hints[:10] { // 10 rows
fmt.Printf("%#v\n", *hint)
}
Another solution (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)
Edit 2
Use []int{skip, limit}
on $slice
to support skip and limit.
selector := bson.M{"hints": bson.M{"$slice": []int{0, 10}}}