LoginSignup
6
6

More than 5 years have passed since last update.

GoでMongoDBを使う勉強(続報)

Posted at

 以前に投稿したGoでMongoDBを使う方法に関してもう少し自分なりに改良を加え勉強してみました。使用したサンプルはいつものように
    https://gist.github.com/border/3489566
を使用しました。
 こちらのサンプルはテストということなので基本的な使い方はすべてmainに書かれています。実際に運用する際はModule化する必要があるのでどのようにModule化すればよいかをテストしてみました。

sanple.go
package main

import (
    "fmt"
    "labix.org/v2/mgo"
    "labix.org/v2/mgo/bson"
    "time"
)

type Person struct {
    ID        bson.ObjectId `bson:"_id,omitempty"`
    Name      string
    Phone     string
    Timestamp time.Time
}

var (
    IsDrop = true
)

ここまでは同じです。DBにアクセスするsession形成をmodule化してみます。

sample.go
func CreateSession(dialURL string) (session *mgo.Session, err error) {
    newSession, err := mgo.Dial(dialURL)
    if err != nil {
        panic(err)
    }

    newSession.SetMode(mgo.Monotonic, true)

    // Drop Database
    if IsDrop {
        err = newSession.DB("test").DropDatabase()
        if err != nil {
            panic(err)
        }
    }

    return newSession, err
}

 このような感じです。私がはまったのはreturnでnewSessionとerrを返すところです。Go特有の記述ですね。
 引数としてdialURLを取ります。引数を使用しmgo.Dialでsessionを指定します。次にmainでこの関数を呼び出してみます。

sample.go
unc main() {
    session, err := CreateSession("localhost")
    c := session.DB("test").C("people")

    // Index
    index := mgo.Index{
        Key:        []string{"name", "phone"},
        Unique:     true,
        DropDups:   true,
        Background: true,
        Sparse:     true,
    }

    err = c.EnsureIndex(index)
    if err != nil {
        panic(err)
    }
    person1 := &Person{Name: "Ale", Phone: "+55 53 1234 4321", Timestamp: time.Now()}
    person2 := &Person{Name: "Cla", Phone: "+66 33 1234 5678", Timestamp: time.Now()}
    person3 := &Person{Name: "Kazu", Phone: "+77 34 5078 2525", Timestamp: time.Now()}

   err = c.Insert(person1, person2)
    if err != nil {
        panic(err)
    }

    err = c.Insert(person3)
    if err != nil {
        panic(err)
    }

 という感じです。かわっているところは作成してCreateSessionで使用するsessionを形成します。person1,2,3のobjectを個別形成し、c.Insert(...)で導入していきます。実験のために分割してInsertしてみました。問題はないようです。
 これで基礎実験はできたので応用実験としてrevelに接続して実験してみます。

6
6
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
6
6