mongodb 你如何使用mgo从golang的mongodb集合中选择所有记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24681047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you select all records from a mongodb collection in golang using mgo
提问by Dean
In MongoDB doing something like db.mycollection.find()
returns all documents in a collection.
在 MongoDB 中,执行类似db.mycollection.find()
返回集合中的所有文档的操作。
When working in GoLang using the package labix.org/v2/mgoand I do for example:
当使用包labix.org/v2/mgo在 GoLang 中工作时,我会这样做:
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.
它抱怨它需要以界面的形式输入。我需要做的就是检索所有文档并遍历它们并暂时显示每个文档。我如何实现这种效果?我见过的所有例子似乎都有过滤器。
回答by Dean
Found a solution:
找到了解决办法:
var results []client
err := db.C("client").Find(nil).All(&results)
if err != nil {
// TODO: Do something about the error
} else {
fmt.Println("Results All: ", results)
}
回答by sudheer nunna
func (uc UserController) GetUsersList(w http.ResponseWriter,r *http.Request,p httprouter.Params){
var u []models.User
// Fetch user
if err := uc.session.DB("mydb").C("users").Find(nil).All(&u); err != nil {
w.WriteHeader(404)
fmt.Println("Results All: ", u)
return
}
uj, _ := json.Marshal(u)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
fmt.Fprintf(w, "%s", uj)
}