Use Go to display data from MongoDB?

I’m doing a POC (proof of concept) sample program to connect to my mongo database - ‘test’ and now I want to be able to display the collections and documents from Go.

Here’s my code so far.

package main

import (

type DocumentData struct {
   Name string `bson:"name"`
   Class string `bson:"class"`

func main() {
   // Connection
   session, err := mgo.Dial("localhost:27017")
   if err != nil {
      fmt.Printf("Can't connect", err)
   defer session.Close()

   c := session.DB("test").C("testCollections") // My mongo DB is called 'test' and collection: 'testCollections'

   // Find data

1 Like

Here’s the doc about retrieving One item from the collection:

1 Like

Thanks!! I found out to retrieve the data, you can just use Find. I added this to where I commented // Find data:

    err = c.Find(nil).All(&documentData) // Find all documents
 // err = c.Find(DocumentData{Name: "Tony"}).One(&documentData) // Find specific document
       if err != nil {
          fmt.Println("Error document(s)", err)
       fmt.Println("Documents found: \n", documentData)

One minor suggestion on finding records

err = c.Find(bson.M{"Name":"Tony"}).One(&documentData) // using bson will give you alot of flexibility

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.