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
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
.
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)
Use []int{skip, limit}
on the $slice
, to support skip and limit.
selector := bson.M{"hints": bson.M{"$slice": []int{0, 10}}}