PythonとMongodbデータベースの間の操作方法を簡単に分析します。
MongoDBは現在最も人気のあるNoSQLデータベースの一つで、使用するデータタイプのBSON(JSONに類似)です。
1.Mongodbとpymongoの取り付け
Mongodbのインストールと配置
Mongodbのインストール教程はネットで検索してください。インストールが完了したら、 以下の構成手順を行います。
1.1 Mongodbデータファイルの保存ディレクトリであるディレクトリを作成します。
*注:本人が使っているのはrootユーザーではないので、ディレクトリの所有者を変更します。*
第一条コマンドは指定ポートと保存経路、第二条はmongodbデータベースを実行する。
mongodbはデータをキーとして記憶していますので、Pythonでフィールドを使ってデータを挿入します。
insertの方法:
5 b 3 a 1942971951218 d 41 c 02 b
[ObjectId('5 b 3 a 1942971951218 d 41 c 02 c')、Object Id('5 b 3 a 1942971951218 d 41 c 02 d')
公式の推奨:
4.1 $setを使用しないでデータを更新します。
違いを紹介します。
4.3 違います
使用:
4.4 udate_oneとudate_マンリーの違い:
{ok':1、'n':1}
1
2
6.その他
上記でよく使われている以外に、find_も含まれています。one.and_delete()検索後削除、find_one.and_replace()検索した後に換えて、百度深く理解することができる興味があります。
締め括りをつける
以上は小编が绍介したPythonとMongodbデータベースの间の操作方法です。皆さんに助けてほしいです。もし何か疑问がありましたら、メッセージをください。小编はすぐに返事します。ここでも私たちのサイトを応援してくれてありがとうございます。
本文があなたのためになると思ったら、転載を歓迎します。出所を明記してください。ありがとうございます。
1.Mongodbとpymongoの取り付け
Mongodbのインストールと配置
Mongodbのインストール教程はネットで検索してください。インストールが完了したら、 以下の構成手順を行います。
1.1 Mongodbデータファイルの保存ディレクトリであるディレクトリを作成します。
*注:本人が使っているのはrootユーザーではないので、ディレクトリの所有者を変更します。*
sudo mkdir /data
sudo chown -R python:python /data
mkdir /data/db
1.2それぞれコマンドを実行する:第一条コマンドは指定ポートと保存経路、第二条はmongodbデータベースを実行する。
mongod --port 27017 --dbpath /data/db
mongo --port 27017
1.3 pymonoをインストールするsudo pip3 install pymongo
2.データベースの接続、データベースの指定、集合の指定、データの挿入:mongodbはデータをキーとして記憶していますので、Pythonでフィールドを使ってデータを挿入します。
import pymongo
# mongodb
client = pymongo.MongoClient('mongodb://localhost:27017/')
#
db = client.test4
#
collection = db.students
#
student1 = {
'id': '201801',
'name': 'Jack',
'age': 20,
'gender': 'male'
}
student2 = {
'id': '201802',
'name': 'Tom',
'age': 22,
'gender': 'male'
}
student3 = {
'id': '201803',
'name': 'Rose',
'age': 21,
'gender': 'female'
}
student4 = {
'id': '201804',
'name': 'Mike',
'age': 20,
'gender': 'female'
}
student5 = {
'id': '201805',
'name': 'Ray',
'age': 20,
'gender': 'female'
}
student6 = {
'id': '201806',
'name': 'Alan',
'age': 21,
'gender': 'male'
}
#
result1 = collection.insert_one(student1)
print(result1)
print(result1.inserted_id)
# #
result2 = collection.insert_many([student2, student3, student4, student5, student6])
print(result2)
print(result2.inserted_ids)
実行結果:insertの方法:
5 b 3 a 1942971951218 d 41 c 02 b
[ObjectId('5 b 3 a 1942971951218 d 41 c 02 c')、Object Id('5 b 3 a 1942971951218 d 41 c 02 d')
公式の推奨:
<pymongo.results.InsertOneResult object at 0x7fa4cc363ec8>
5b3a1942971951218d41c02e
<pymongo.results.InsertManyResult object at 0x7fa4cc363f08>
[ObjectId('5b3a1942971951218d41c02f'), ObjectId('5b3a1942971951218d41c030')]
3.クエリー、カウント、並べ替え、オフセット:
import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
#
print(' ','='*50)
result = collection.find_one({'name': 'Jack'})
print(result)
print(' ','='*50)
#
for res in collection.find({'age': {'$mod': [5, 0]}}):
print(res)
#
print(' ','='*50)
count = collection.find({'age': {'$mod': [5, 0]}}).count()
print(count)
#
print(' ','='*50)
results = collection.find().sort('name', pymongo.ASCENDING) # , pymongo.DESCENDING
print([result['name'] for result in results])
#
print(' ','='*50)
results = collection.find().sort('name', pymongo.ASCENDING).skip(2) # 2 ,
print([result['name'] for result in results])
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2) # 2
print([result['name'] for result in results])
find({‘age': {'$mod': [5, 0]}}): 5 0 . , .
実行結果:
==================================================
{'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 20, 'gender': 'male'}
==================================================
{'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 20, 'gender': 'male'}
{'_id': ObjectId('5b3a1942971951218d41c02e'), 'id': '201804', 'name': 'Mike', 'age': 20, 'gender': 'female'}
{'_id': ObjectId('5b3a1942971951218d41c02f'), 'id': '201805', 'name': 'Ray', 'age': 20, 'gender': 'female'}
==================================================
3
==================================================
['Alan', 'Jack', 'Mike', 'Ray', 'Rose', 'Tom']
==================================================
['Mike', 'Ray', 'Rose', 'Tom']
['Mike', 'Ray']
4.更新:4.1 $setを使用しないでデータを更新します。
import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
#
condition = {'name': 'Jack'}
student = collection.find_one(condition) # condition
print(' : ', student)
student['age'] = 22 #
result = collection.update(condition, student) # student condition
print(' ', collection.find_one(condition))
#
print(result) #ok=1 , nModified
実行結果:
: {'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 20, 'gender': 'male'}
{'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 22, 'gender': 'male'}
{'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}
4.2 $setを使ってデータを更新します。
import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
# $set
condition = {'name': 'Jack'}
student = collection.find_one(condition) # condition
print(' : ', student)
student['age'] = 23 #
result = collection.update(condition, {'$set': student}) # student condition, $set
print(' ', collection.find_one(condition))
#
print(result) #ok=1 , nModified
実行結果:
: {'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 22, 'gender': 'male'}
{'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 23, 'gender': 'male'}
{'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}
データの更新は使用と不適用を比較しますが、この時点では特に違いがありません。違いを紹介します。
4.3 違います
import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
# $set
print(' : ')
condition = {'name': 'Jack'}
student = collection.find_one(condition) # condition
print(' : ', student)
student = {
'id': '201803',
'name': 'Jack',
'age': 20,
'gender': 'female',
'mother': "Jack's mother"
}
result = collection.update(condition, {'$set': student}) # student condition
print(' ', collection.find_one(condition))
#
print(result) #ok=1 , nModified
#
print()
print('='*20, ' ', '='*20)
print()
print(' : ')
condition = {'name': 'Jack'}
student = collection.find_one(condition) # condition
print(' : ', student)
student = {
'id': '201803',
'name': 'Jack',
'age': 20,
'gender': 'female',
'father': "Jack's father"
}
result = collection.update(condition, student) # student condition
print(' ', collection.find_one(condition))
#
print(result) #ok=1 , nModified
実行結果:使用:
: {'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 23, 'gender': 'male'}
{'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201803', 'name': 'Jack', 'age': 20, 'gender': 'female', 'mother': "Jack's mother"}
{'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}
=============================================================================================
:
: {'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201803', 'name': 'Jack', 'age': 20, 'gender': 'female', 'mother': "Jack's mother"}
{'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201803', 'name': 'Jack', 'age': 20, 'gender': 'female', 'father': "Jack's father"}
{'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}
上記の運転結果を分析すると、$setを使用する場合、更新データに元のデータがないフィールドがあれば、元のデータにフィールドを追加します。フィールドは削除されません。逆にsetを使用しない場合は、元のデータから更新データがないフィールドを削除し、フィールドを追加します。fatherフィールドが追加されました。元のデータを完全に更新データに置き換えることもできます。4.4 udate_oneとudate_マンリーの違い:
import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
#
#update_one update_many
print('update_one: ')
condition = {'age': {'$gt': 20}}
result = collection.update_one(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)
#
print()
print('='*20, ' ', '='*20)
print()
print('update_many: ')
condition = {'age': {'$gt': 20}}
result = collection.update_many(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)
実行結果:
update_one:
<pymongo.results.UpdateResult object at 0x7f6cace0f9c8>
1 1
==================== ====================
update_many:
<pymongo.results.UpdateResult object at 0x7f6cace0fa88>
3 3
12345678910
{‘age': {'$gt': 20}} 20 , {‘inc': {‘age': 1}} +1
5.削除:
import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
#
result = collection.remove({'name': 'Jack'})
print(result)
#
result = collection.delete_one({'age': {'$gt': 20}})
print(result.deleted_count)
result = collection.delete_many({'age': {'$gt': 20}})
print(result.deleted_count)
実行結果:{ok':1、'n':1}
1
2
6.その他
上記でよく使われている以外に、find_も含まれています。one.and_delete()検索後削除、find_one.and_replace()検索した後に換えて、百度深く理解することができる興味があります。
締め括りをつける
以上は小编が绍介したPythonとMongodbデータベースの间の操作方法です。皆さんに助けてほしいです。もし何か疑问がありましたら、メッセージをください。小编はすぐに返事します。ここでも私たちのサイトを応援してくれてありがとうございます。
本文があなたのためになると思ったら、転載を歓迎します。出所を明記してください。ありがとうございます。