Golang で MongoDB のデータを読みます。
次のプログラムで作成したデータを読みます。
Golang で MongoDB のデータを作成 (Create)
ライブラリーのインストール
go get gopkg.in/mgo.v2
go get github.com/joho/godotenv
mongo_read.go
// ---------------------------------------------------------------
//
// mongo_read.go
//
// Jun/11/2019
// ---------------------------------------------------------------
package main
import (
"fmt"
"os"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"time"
"strconv"
"github.com/joho/godotenv"
)
type City struct {
ID bson.ObjectId `bson:"_id,omitempty"`
Key string
Name string
Population int
Date_mod time.Time
}
// ---------------------------------------------------------------
func main() {
fmt.Fprintf (os.Stderr,"*** 開始 ***\n")
err := godotenv.Load(".env")
if err != nil {
panic(err)
}
user := os.Getenv("user")
password := os.Getenv("password")
mongoDBDialInfo := &mgo.DialInfo{
Addrs: []string{"127.0.0.1"},
Timeout: 60 * time.Second,
Username: user,
Password: password,
}
session, err := mgo.DialWithInfo(mongoDBDialInfo)
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
db_name := "city"
cc := session.DB(db_name).C("saitama")
var results []City
err = cc.Find(bson.M{}).Sort("key").All(&results)
if err != nil {
panic(err)
}
fmt.Println("len(results): ", len(results))
for _,value := range results {
str_out := value.Key + "\t" + value.Name + "\t" + strconv.Itoa(value.Population) + "\t" + value.Date_mod.String()
fmt.Println(str_out)
}
fmt.Fprintf (os.Stderr,"*** 終了 ***\n")
}
// ---------------------------------------------------------------
Makefile
mongo_read: mongo_read.go
go build mongo_read.go
clean:
rm -f mongo_read
.env
user = '******'
password = '******'
実行コマンド
./mongo_read
次のバージョンで確認しました。
$ go version
go version go1.13.8 linux/amd64
$ mongo --version
MongoDB shell version v3.6.8
git version: 8e540c0b6db93ce994cc548f000900bdc740f80a
OpenSSL version: OpenSSL 1.1.1f 31 Mar 2020
allocator: tcmalloc
modules: none
build environment:
distarch: x86_64
target_arch: x86_64