使用Go检索MongoDB文档时出现的问题
我有下面的代码,我不知道为什么它不返回一段注释。我正在使用labix.org上的mgo库连接到MongoDB,并遵循他们的在线文档使用Go检索MongoDB文档时出现的问题,mongodb,go,mgo,Mongodb,Go,Mgo,我有下面的代码,我不知道为什么它不返回一段注释。我正在使用labix.org上的mgo库连接到MongoDB,并遵循他们的在线文档 type Note struct { Url string Title string Date string Body string } func loadNotes() ([]Note) { session, err := mgo.Dial("localhost") if err != nil {
type Note struct {
Url string
Title string
Date string
Body string
}
func loadNotes() ([]Note) {
session, err := mgo.Dial("localhost")
if err != nil {
panic(err)
}
defer session.Close()
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
c := session.DB("test").C("notes")
notes := []Note{}
iter := c.Find(nil).Limit(100).Iter()
err = iter.All(¬es)
if err != nil {
panic(iter.Err())
}
return notes
}
func main() {
notes := loadNotes()
for note := range notes {
fmt.Println(note.Title)
}
}
如果我只是打印出notes
我会得到一个看起来像两个结构片的东西,但我不能通过notes.Title
或类似的方式访问它们
[{ Some example title 20 September 2012 Some example content}]
这就是我的文档的外观:
> db.notes.find()
{ "_id" : "some-example-title", "title" : "Some example title", "date" : "20 September 2012", "body" : "Some example content" }
真正的问题是,它返回的注释是一个大片段,而不是注释{}
(我想是吧?)
如果我做了一些明显错误的事情,任何洞察都会有所帮助。iter.All()立即将整个结果集检索到一个片段中。如果只需要一行,请使用iter.Next()。看这对我来说似乎很有效。notes是您所指出的结构的一部分
for _, n := range notes {
n.Title // do something with title
n.Url // do something with url
}
或者,如果您只想要第一个:
注释[0]。标题
也可以
结构片不能像结构本身一样进行索引,因为它不是结构。您的问题在于:
for note := range notes {
fmt.Println(note.Title)
}
应改为:
for _, note := range notes {
fmt.Println(note.Title)
}
在片上使用range语句返回成对的i,v
,其中i是片中的索引,v是该片中索引处的项。由于省略了第二个值,因此在索引上循环,而不是在Note
值上循环
在规范的RangeClause部分:^我让这篇文章更具描述性。