2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Golang で MongoDB のデータを更新 (Update)

Last updated at Posted at 2018-05-22

Golang で MongoDB のデータを更新します。
次のプログラムで作成したデータを更新します。
Golang で MongoDB のデータを作成 (Create)

ライブラリーのインストール

go get gopkg.in/mgo.v2
go get github.com/joho/godotenv
mongo_update.go
// ---------------------------------------------------------------
//
//	mongo_update.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")
	key_in := os.Args[1]
	population_in,_ := strconv.Atoi (os.Args[2])

	fmt.Printf ("key_in = %s\t" , key_in)
	fmt.Printf ("population_in = %d\n" , population_in)
	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")

	colQuerier := bson.M{"key": key_in}
	change := bson.M{"$set": bson.M{"population": population_in, "date_mod": time.Now()}}
	err = cc.Update(colQuerier, change)
	if err != nil {
		panic(err)
	}

	var results []City
	err = cc.Find(bson.M{"key": key_in}).Sort("key").All(&results)

	if err != nil {
		panic(err)
	}
	fmt.Println("Results All: ", results)

	fmt.Fprintf (os.Stderr,"*** 終了 ***\n")
}

// ---------------------------------------------------------------
Makefile
mongo_update: mongo_update.go
	go build mongo_update.go
clean:
	rm -f mongo_update
.env
user = '******'
password = '******'

実行コマンドの例

./mongo_update t1166 9347600

次のバージョンで確認しました。

$ 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
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?