How do you select all records from a mongodb collection in golang using mgo
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)
}
Related videos on Youtube
Dean
I'm a Software Developer / Architect based in Centurion South Africa with a strong passion for writing Software. I'm a Linux guy that loves open source languages. My favourite languages are PHP, Python and GoLang and my flavour of Linux is Kali :-) Preferred console is xbox (GT:deancarlotinash). Feel free to ask me anything ;-)
Updated on October 17, 2020Comments
-
Dean over 3 years
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:
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.
-
bohdan_trotsenko almost 10 yearsgetting nil from a database is a weak reason to
panic
-
amlwwalker about 8 yearshowever will get the user of the above code to actually read it and decide how to deal with the
nil
. From the perspective of someone coming here and copy/pasting that code being highly likely, this is a good way to get them to at least think about it.... -
muthukumar selvaraj almost 6 yearsyou can use
db.c("client").Find(bson.M{}).All(&result)