LoginSignup
8
3

More than 5 years have passed since last update.

MongoDB 4.0 のトランザクション機能をMongoシェルから試す

Posted at

MacOSにMongoDB 4.0をインストールしてトランザクションを試します。

まずはMongoDB 4.0をダウンロードして解凍

wget https://fastdl.mongodb.org/osx/mongodb-osx-ssl-x86_64-4.0.0.tgz
tar zxvf mongodb-osx-ssl-x86_64-4.0.0.tgz

データディレクトリを作る

cd mongodb-osx-x86_64-4.0.0/
mkdir data

MongoDBをレプリカセットモードで起動(通常モードだとトランザクションは使えないため)

./bin/mongod --dbpath data --replSet rs1

別のターミナルでMongoシェルで接続して、1台のmongodからなるレプリカセットを設定して、初期化

./bin/mongo
> rs.initiate({"_id":"rs1",members:[{_id:0,host:"<IPアドレス>:27017"}]})

プロンプトが rs1:PRIMARY>  になればレプリカセット構築完了OK

testデータベース のmycolコレクションに、まず1つデータを入れる

rs1:PRIMARY> use test
switched to db test
rs1:PRIMARY> db.mycol.insert({"a":1})
WriteResult({ "nInserted" : 1 })

トランザクションを開始しして、2つ目のデータを入れる

rs1:PRIMARY> session = db.getMongo().startSession()
session { "id" : UUID("0277f85e-b00f-4d3e-8398-7afa22fc5e97") }
rs1:PRIMARY> session.startTransaction()
rs1:PRIMARY> mycol = session.getDatabase("test").mycol
test.mycol
rs1:PRIMARY> mycol.insert({"a":2})
WriteResult({ "nInserted" : 1 })

この時点では、他のクライアントからは{"a":2}のドキュメントは見えない

トランザクションをコミットする

rs1:PRIMARY> session.commitTransaction()

これで、他のクライアントからも{"a":2}のドキュメントは見えるようになった

8
3
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
8
3