Python+MongoDBメモ
Pythonを使ってMongoDBを操作したかったので色々調べたのでメモ
随時更新予定
Pythonドライバをインストール
pip install pymongo dnspython
MongoDB接続
import pymongo
client = pymongo.MongoClient(
"mongodb+srv://[User]:[Password]@cluster0.8tpbm.mongodb.net/myFirstDatabase?retryWrites=true&w=majority")
DB追加、選択
testが存在しない場合は新規作成
db = client.test
コレクション追加、選択
testが存在しない場合は新規作成
collection = db.test
データ追加
account = {
'account_id': 100001,
'limit': 9000,
'products': ['TEST1', 'TEST1-1']
}
result = collection.insert_one(account)
print(result.inserted_id)
複数件のデータ追加
accounts = [
{'account_id': 100002, 'limit': 9000, 'products': ['TEST2', 'TEST2-1']},
{'account_id': 100003, 'limit': 9000, 'products': ['TEST3', 'TEST3-1']}
]
result = collection.insert_many(accounts)
print(result.inserted_ids)
データ取得
account = collection.find_one({"account_id": 123456})
print(account)
複数件のデータ取得
accounts = collection.find({'$or': [{'account_id': 100002}, {'account_id': 100003}]},
sort=[('account_id', pymongo.ASCENDING)])
result = [v for v in accounts]
print(result)
データ更新
update = collection.update_one({"account_id": 100001}, {'$set': {'limit': 8000}})
print(update.matched_count)
複数件のデータ更新
update = collection.update_many({'$or': [{'account_id': 100002}, {'account_id': 100003}]},
{'$set': {'limit': 9000}})
print(update.matched_count)
データ削除
result = collection.delete_one({"account_id": 100001})
print(result.deleted_count)
複数件のデータ削除
result = collection.delete_many({'$or': [{'account_id': 100002}, {'account_id': 100003}]})
print(result.deleted_count)