如何在使用mgo的golang中选择mongodb集合中的所有记录?

huangapple go评论114阅读模式
英文:

How do you select all records from a mongodb collection in golang using mgo

问题

在MongoDB中,执行类似db.mycollection.find()的操作会返回集合中的所有文档。

在使用Go语言的labix.org/v2/mgo包时,如果我执行以下操作:

  1. query := db.C("client").Find();

它会报错,要求以接口的形式提供输入。我只需要检索所有文档并遍历它们,目前不需要任何筛选条件。我该如何实现这个效果?我看到的所有示例似乎都有筛选条件。

英文:

In MongoDB doing something like db.mycollection.find() returns all documents in a collection.

When working in GoLang using the package labix.org/v2/mgo and I do for example:

  1. query := db.C("client").Find();

It complains that it requires input in the form of an interface. All I need to do is retrieve all documents and iterate through them and display each one for now. How do I achieve this effect? All examples I have seen seem to have filters in place.

答案1

得分: 47

找到了一个解决方案:

  1. var results []client
  2. err := db.C("client").Find(nil).All(&results)
  3. if err != nil {
  4. // TODO: 对错误进行处理
  5. } else {
  6. fmt.Println("全部结果:", results)
  7. }
英文:

Found a solution:

  1. var results []client
  2. err := db.C("client").Find(nil).All(&results)
  3. if err != nil {
  4. // TODO: Do something about the error
  5. } else {
  6. fmt.Println("Results All: ", results)
  7. }

答案2

得分: 0

func (uc UserController) GetUsersList(w http.ResponseWriter, r *http.Request, p httprouter.Params) {

  1. var u []models.User
  2. // 获取用户
  3. if err := uc.session.DB("mydb").C("users").Find(nil).All(&u); err != nil {
  4. w.WriteHeader(404)
  5. fmt.Println("Results All: ", u)
  6. return
  7. }
  8. uj, _ := json.Marshal(u)
  9. w.Header().Set("Content-Type", "application/json")
  10. w.WriteHeader(200)
  11. fmt.Fprintf(w, "%s", uj)

}

英文:
  1. func (uc UserController) GetUsersList(w http.ResponseWriter,r *http.Request,p httprouter.Params){
  2. var u []models.User
  3. // Fetch user
  4. if err := uc.session.DB("mydb").C("users").Find(nil).All(&u); err != nil {
  5. w.WriteHeader(404)
  6. fmt.Println("Results All: ", u)
  7. return
  8. }
  9. uj, _ := json.Marshal(u)
  10. w.Header().Set("Content-Type", "application/json")
  11. w.WriteHeader(200)
  12. fmt.Fprintf(w, "%s", uj)
  13. }

huangapple
  • 本文由 发表于 2014年7月10日 23:53:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/24681047.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定