LoginSignup
9
10

More than 3 years have passed since last update.

Pythonでmongodbを操作する~その4:insert編~

Posted at

当記事の記載範囲

この記事ではPythonでmongodbに接続してから、insert(SQLで言ってもinsert)の使い方について記載します。
内容としては以下になります。
1. insert_one
2. insert_many

mongodbの起動やpymongoのインストール方法については以下の記事をご覧いただければ幸いです。
https://qiita.com/bc_yuuuuuki/items/2b92598434f6cc320112

準備データ

mongodbの準備データは以下のとおりです。

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB
> show collections
employee
log
salary
> db.salary.find()
{ "_id" : ObjectId("5d4acf84de925ae437e2c124"), "name" : "佐藤", "salary" : 400000 }
{ "_id" : ObjectId("5d4acf84de925ae437e2c125"), "name" : "田中", "salary" : 500000 }
{ "_id" : ObjectId("5d4b81a4de925ae437e2c126"), "name" : "山田", "salary" : 500000 }

Pythonでinsertを使ってみる

まずはinsert_oneから使ってみます。

insert_oneの使い方

早速、サンプルのコードです。
内容はinsert前のデータ取得、insert_one、insert後のデータ取得を行っています。

MongoInsertSample.py
from pymongo import MongoClient

class MongoInsertSample(object):

    def __init__(self, dbName, collectionName):
        self.client = MongoClient()
        self.db = self.client[dbName]
        self.collection = self.db.get_collection(collectionName)

    def find(self, projection=None,filter=None, sort=None):
        return self.collection.find(projection=projection,filter=filter,sort=sort)

    def insert_one(self, document):
        return self.collection.insert_one(document)

    def insert_many(self, documents):
        return self.collection.insert_many(documents)

mongo = MongoInsertSample('test', 'salary')
find = mongo.find()
print('--------------------登録前--------------------')
for doc in find:
    print(doc)

print('-------------------登録情報-------------------')
result = mongo.insert_one({'name':'加藤','salary':400000})
print(type(result))
print(result)
print(result.inserted_id)

print('--------------------登録後--------------------')
find = mongo.find()
for doc in find:
    print(doc)

実行結果

--------------------登録前--------------------
{'_id': ObjectId('5d4acf84de925ae437e2c124'), 'name': '佐藤', 'salary': 400000.0}
{'_id': ObjectId('5d4acf84de925ae437e2c125'), 'name': '田中', 'salary': 500000.0}
{'_id': ObjectId('5d4b81a4de925ae437e2c126'), 'name': '山田', 'salary': 500000}
-------------------登録情報-------------------
<class 'pymongo.results.InsertOneResult'>
<pymongo.results.InsertOneResult object at 0x000001E7054CD748>
5d4f74cb42f88d7822517a76
--------------------登録後--------------------
{'_id': ObjectId('5d4acf84de925ae437e2c124'), 'name': '佐藤', 'salary': 400000.0}
{'_id': ObjectId('5d4acf84de925ae437e2c125'), 'name': '田中', 'salary': 500000.0}
{'_id': ObjectId('5d4b81a4de925ae437e2c126'), 'name': '山田', 'salary': 500000}
{'_id': ObjectId('5d4f74cb42f88d7822517a76'), 'name': '加藤', 'salary': 400000}

insert_oneの戻り値として’pymongo.results.InsertOneResult'のクラスが戻ってくるようです。
このクラスには登録したdocumentsの主キー(_id)を取得できるようです。

insert_manyの使い方

MongoInsertSample.pyを一部変更します。

(抜粋)MongoInsertSample.py
mongo = MongoInsertSample('test', 'salary')
find = mongo.find()
print('--------------------登録前--------------------')
for doc in find:
    print(doc)

print('-------------------登録情報-------------------')
result = mongo.insert_many([{'name':'加藤','salary':400000},{'name':'松井','salary':500000}])
print(type(result))
print(result)
print(result.inserted_ids)
find = mongo.find()
print('--------------------登録後--------------------')
for doc in find:
    print(doc)

実行結果

--------------------登録前--------------------
{'_id': ObjectId('5d4acf84de925ae437e2c124'), 'name': '佐藤', 'salary': 400000.0}
{'_id': ObjectId('5d4acf84de925ae437e2c125'), 'name': '田中', 'salary': 500000.0}
{'_id': ObjectId('5d4b81a4de925ae437e2c126'), 'name': '山田', 'salary': 500000}
-------------------登録情報-------------------
<class 'pymongo.results.InsertManyResult'>
<pymongo.results.InsertManyResult object at 0x00000249F8ABCD08>
[ObjectId('5d4f814c950945628d663d95'), ObjectId('5d4f814c950945628d663d96')]
--------------------登録後--------------------
{'_id': ObjectId('5d4acf84de925ae437e2c124'), 'name': '佐藤', 'salary': 400000.0}
{'_id': ObjectId('5d4acf84de925ae437e2c125'), 'name': '田中', 'salary': 500000.0}
{'_id': ObjectId('5d4b81a4de925ae437e2c126'), 'name': '山田', 'salary': 500000}
{'_id': ObjectId('5d4f814c950945628d663d95'), 'name': '加藤', 'salary': 400000}
{'_id': ObjectId('5d4f814c950945628d663d96'), 'name': '松井', 'salary': 500000}

注意すべき点は特にないかなと思います。
強いて言えば、insert_oneとinsert_manyの戻り値のクラスが異なります。
登録した情報を取得する時の取得の仕方が少し異なります。
- inserted_id
- inserted_ids

感想

updateと同様にinsertもmongodbのコマンドとパラメーターの設定方法が同じで使いやすいです。

関連記事

9
10
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
9
10