|
I have a collection `users` in which I have two documents.
$ db.users.find({}).pretty() db.users.find({}).pretty()
|
|
{
|
"_id" : ObjectId("5ced40daa900b72809092494"),
|
"name" : "Elon",
|
"age" : 46
|
}
|
{
|
"_id" : ObjectId("5ced40dba900b72809092495"),
|
"name" : "PCP",
|
"age" : 26
|
}
|
|
Use case: Find all user having some filter criteria or not filter criteria.
user.go:
type user struct {
|
Name string `bson:"name"`
|
Age int `bson:"age"`
|
}
|
|
func (u *user) save() error {
|
collection := database.Collection(userCollection)
|
ctx, cancelFunc := context.WithTimeout(context.Background(), 20*time.Second)
|
defer cancelFunc()
|
_, err := collection.InsertOne(ctx, u)
|
return err
|
}
|
|
|
func findAll() ([]user, error) {
|
collection := database.Collection(userCollection)
|
selector := bson.M{}
|
ctx, cancelFunc := context.WithTimeout(context.Background(), 20*time.Second)
|
defer cancelFunc()
|
cur, err := collection.Find(ctx, selector)
|
if err != nil {
|
return nil, err
|
}
|
fmt.Printf("\n all users (for debugging raw bson resp): %s\n", cur.Current.String())
|
|
users := []user{}
|
if err := cur.Decode(&users); err != nil {
|
return nil, err
|
}
|
return users, nil
|
}
|
|
|
main.go
saveUser("Elon", 46)
|
saveUser("PCP", 26)
|
if users, err := findAll(); err != nil {
|
panic(err)
|
} else {
|
fmt.Printf("all users: %v", users)
|
}
|
fmt.Printf("exiting application\n")
|
cur, err := collection.Find(ctx, selector)
|
*is *not working as expected as the output of **
fmt.Printf("\n all users (for debugging raw bson resp): %s\n", cur.Current.String())
|
is an empty string.
|