【问题标题】:Issues retrieving MongoDB documents with Go使用 Go 检索 MongoDB 文档的问题
【发布时间】:2012-09-24 04:09:25
【问题描述】:

我有以下代码,但我不确定它为什么不返回 Notes 片段。我正在使用 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 {
            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(&notes)
    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" }

真正的问题是它将笔记作为一大片返回,而不是Note{}(我认为?)

如果我做的事情明显错误,任何见解都会有所帮助。

【问题讨论】:

  • ^ 我让帖子更具描述性。

标签: mongodb go mgo


【解决方案1】:

你的问题在这里:

for note := range notes {
    fmt.Println(note.Title)
}

应该是:

for _, note := range notes {
    fmt.Println(note.Title)
}

在切片上使用范围语句会返回 i, v 形式的对,其中 i 是切片中的索引,v 是该切片中索引处的项目。由于您省略了第二个值,因此您循环的是索引,而不是 Note 值。

在规范的 RangeClause 部分:http://golang.org/ref/spec#RangeClause

【讨论】:

    【解决方案2】:

    它看起来对我有用。 notes 是您指出的一部分结构。

    for _, n := range notes {
      n.Title // do something with title
      n.Url // do something with url
    }
    

    或者,如果您只想要第一个: notes[0].Title 应该也可以。

    结构切片不能像结构本身一样被索引,因为它不是结构。

    【讨论】:

      【解决方案3】:

      iter.All() 一次将整个结果集检索到一个切片中。如果您只想要一行,请使用 iter.Next()。见https://groups.google.com/forum/#!msg/mgo-users/yUGZi70ik9Y/J8ktshJgF7QJ

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-12
        • 1970-01-01
        相关资源
        最近更新 更多