DEV Community

Yaşar İÇLİ
Yaşar İÇLİ

Posted on

Make the collection find using Go bongo.

For example, we have a collection of users and we want to find all users from this collection.

If you don't have bongo installed, you can install it as follows.

go get github.com/go-bongo/bongo
Enter fullscreen mode Exit fullscreen mode
package main

import (
  "log"

  "github.com/globalsign/mgo/bson"
  "github.com/go-bongo/bongo"
)

type User struct {
  bongo.DocumentBase `bson:",inline"`
  Username          string
}

func main() {

  // Bongo Connection Config
  config := &bongo.Config{
    ConnectionString: "localhost",
    Database:         "test",
  }

  connection, err := bongo.Connect(config)

  if err != nil {
    log.Fatal(err)
  }

  // Let's see how we can get the user list using bongo.

  user := &User{}
  users := []User{}

  find := connection.Collection("users").Find(bson.M{})

  for find.Next(user) {
    users = append(users, *user)
  }

  log.Println(users)

  /*
    2020/01/24 11:12:51 [{{ObjectIdHex("5e29cd071c291d4f567c482c") 2020-01-23 16:42:47.276 +0000 UTC 2020-01-23 16:42:47.276 +0000 UTC true} Testy McGee male} {{ObjectIdHex("5e2a9e84e30560746c0459c9") 2020-01-24 07:36:36.02 +0000 UTC 2020-01-24 07:36:36.02 +0000 UTC true} yasiari İÇLİ ERKEK}]
  */
}
Enter fullscreen mode Exit fullscreen mode

It's simple and short.

Top comments (0)