MongoDB(33) - 一括処理(Bulk)②一括更新

今回は、一括更新(Bulk)に関する操作を行います。

一括更新

順次処理で一括更新を行います。

(並列処理で実行したい場合は、initializeOrderedBulkOp()の代わりにinitializeUnorderedBulkOp()を使います。)

処理の詳細は以下の通りです。

  1. Bulk実行タイプを設定。(1行目)
  2. updateクエリーを設定。(3~5行目)
  3. 一括実行(Bulk実行)。(7行目)

[Mongoシェル]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
> var bulk = db.member.initializeOrderedBulkOp()    //順次処理

> bulk.find({name:'武元'}).updateOne({$set:{age:11}})
> bulk.find({name:'松田'}).updateOne({$set:{age:21}})
> bulk.find({name:'加藤'}).updateOne({$set:{age:31}})

> bulk.execute()
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 0,
"nUpserted" : 0,
"nMatched" : 3,
"nModified" : 3,
"nRemoved" : 0,
"upserted" : [ ]
})

> db.member.find()
{ "_id" : ObjectId("613e8c820fb0f3e6cf9e2b81"), "name" : "武元", "age" : 11 }
{ "_id" : ObjectId("613e8c820fb0f3e6cf9e2b82"), "name" : "松田", "age" : 21 }
{ "_id" : ObjectId("613e8c820fb0f3e6cf9e2b83"), "name" : "加藤", "age" : 31 }

問題なく3つのドキュメントの年齢(age)を更新することができました。

Pythonで操作

上記の処理をPythonで行うと、次のようになります。

[ソースコード]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import pymongo
from pymongo import MongoClient
from pymongo import UpdateOne
from pymongo.errors import BulkWriteError

# MongoDB操作用のインスタンスを作成
client = MongoClient() # [IPとポートを指定する場合] MongoClient('10.200.243.203', 27017')

# データベースの取得
db1 = client.db1

# 一括更新
requests = [
UpdateOne({'name':'武元'}, {'$set':{'age':11}}),
UpdateOne({'name':'松田'}, {'$set':{'age':21}}),
UpdateOne({'name':'加藤'}, {'$set':{'age':31}})
]

try:
db1.member.bulk_write(requests) # 順次処理
# db.member.bulk_write(requests, ordered=False) # 並列処理
except BulkWriteError as bwe:
pprint(bwe.details)

# 更新内容の確認
docs = db1.member.find()
for doc in docs:
print(doc)

次回は、一括入れ替え処理を行います。