Skip to content

Instantly share code, notes, and snippets.

@sonyarianto
Last active November 27, 2018 09:02
Show Gist options
  • Save sonyarianto/150a931a0863db175dc0532bda91a4d1 to your computer and use it in GitHub Desktop.
Save sonyarianto/150a931a0863db175dc0532bda91a4d1 to your computer and use it in GitHub Desktop.
Simple query MongoDB with Go (Part 1)

MongoDB Data

[{
    "title" : "Hello World",
    "slug" : "hello-world",
    "short_description" : "Hello World is the standard ritual for us when learning new programming language. It's good for you mind and soul hahaha!",
    "tags" : [ 
        {
            "tag" : "beginner"
        }, 
        {
            "tag" : "hello world"
        }
    ],
    "content_file" : "hello-world.md"
},
{
    "title" : "MySQL Demo",
    "slug" : "mysql-demo",
    "short_description" : "MySQL demo short description",
    "tags" : [ 
        {
            "tag" : "beginner"
        }, 
        {
            "tag" : "mysql"
        }
    ]
}]

Here is the code.

package main

import (
	"github.com/mongodb/mongo-go-driver/bson/objectid"
	"github.com/mongodb/mongo-go-driver/mongo"
	"log"
)

type Tag struct {
	Tag string `bson:"tag"`
}

type Content struct {
	Id               objectid.ObjectID `bson:"_id" json:"_id"`
	Title            string            `bson:"title" json:"title"`
	Slug             string            `bson:"slug" json:"slug"`
	ShortDescription string            `bson:"short_description" json:"short_description"`
	ContentFile      string            `bson:"content_file" json:"content_file"`
	Tags             []Tag             `bson:"tags" json:"tags"`
}

func main() {
	// Prepare database.
	client, err := mongo.NewClient("mongodb://root:mongodbpassword@localhost:32768")
	if err != nil {
		log.Fatal(err)
	}

	// Connect to database.
	err = client.Connect(nil)
	if err != nil {
		log.Fatal(err)
	}

	// Select a database.
	db := client.Database("go_db")

	// Do the query to a collection on database.
	c, err := db.Collection("sample_content").Find(nil, nil)
	if err != nil {
		log.Fatal(err)
	}

	defer c.Close(nil)

	var content []Content

	// Start looping on the query result.
	for c.Next(nil) {
		eachContent := Content{}

		err := c.Decode(&eachContent)
		if err != nil {
			log.Fatal(err)
		}

		content = append(content, eachContent)

		log.Println(eachContent)
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment