1.Pymongoインストール
安装pymongo:
pip install pymongo
- プログラムは、Pythonを使用することができるようにPyMongoは、ドライバでのMongoDB Pythonで書かれ、データベースと
2.Pymongo方法
insert_one()
:レコードを挿入します。insert()
:複数のレコードを挿入します。find_one()
:レコードを照会し、パラメーターを指定せずに戻るにはパラメータのプレス条件で、最初のレコードを返します。find()
:パラメータを持たないクエリ複数のレコード、基準に従ってパラメータを返すようにして、すべてのレコードを返します。count()
:レコードの合計数を表示。create_index()
:インデックスを作成します。update_one()
第1のデータと一致するように更新。update()
:一致するすべてのデータを更新します。remove()
:条件をドロップする手段が参加して、すべてのレコードを削除することを意味パラメータなしで、レコードを削除します。delete_one()
:単一レコードを削除します。delete_many()
:複数のレコードを削除します。
操作3.Pymongo
- Viewデータベース
from pymongo import MongoClient
connect = MongoClient(host='localhost', port=27017, username="root", password="123456")
connect = MongoClient('mongodb://localhost:27017/', username="root", password="123456") print(connect.list_database_names())
- データベースインスタンスへのアクセス
test_db = connect['test']
- 取得コレクションの例
collection = test_db['students']
- 文書の行、行のクエリ文書を挿入し、文書の行が値をとります
from pymongo import MongoClient
from datetime import datetime
connect = MongoClient(host='localhost', port=27017, username="root", password="123456",) # 获取db test_db = connect['test'] # 获取collection collection = test_db['students'] # 构建document document = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"], "date": datetime.now()} # 插入document one_insert = collection.insert_one(document=document) print(one_insert.inserted_id) # 通过条件过滤出一条document one_result = collection.find_one({"author": "Mike"}) # 解析document字段 print(one_result, type(one_result)) print(one_result['_id']) print(one_result['author']) 注意:如果需要通过id查询一行document,需要将id包装为ObjectId类的实例对象 from bson.objectid import ObjectId collection.find_one({'_id': ObjectId('5c2b18dedea5818bbd73b94c')})
- 複数の行の文書、複数行のクエリ文書を挿入し、行数の文書コレクションを参照してください
from pymongo import MongoClient
from datetime import datetime
connect = MongoClient(host='localhost', port=27017, username="root", password="123456",) # 获取db test_db = connect['test'] # 获取collection collection = test_db['students'] documents = [{"author": "Mike","text": "Another post!","tags": ["bulk", "insert"], "date": datetime(2009, 11, 12, 11, 14)}, {"author": "Eliot", "title": "MongoDB is fun", "text": "and pretty easy too!", "date": datetime(2009, 11, 10, 10, 45)}] collection.insert_many(documents=documents) # 通过条件过滤出多条document documents = collection.find({"author": "Mike"}) # 解析document字段 print(documents, type(documents)) print('*'*300) for document in documents: print(document) print('*'*300) result = collection.count_documents({'author': 'Mike'}) print(result)
- 範囲クエリの比較
from pymongo import MongoClient
from datetime import datetime
connect = MongoClient(host='localhost', port=27017, username="root", password="123456",) # 获取db test_db = connect['test'] # 获取collection collection = test_db['students'] # 通过条件过滤时间小于datetime(2019, 1,1,15,40,3) 的document documents = collection.find({"date": {"$lt": datetime(2019, 1,1,15,40,3)}}).sort('date') # 解析document字段 print(documents, type(documents)) print('*'*300) for document in documents: print(document)
- インデックスを作成します
from pymongo import MongoClient
import pymongo
from datetime import datetime connect = MongoClient(host='localhost', port=27017, username="root", password="123456",) # 获取db test_db = connect['test'] # 获取collection collection = test_db['students'] # 创建字段索引 collection.create_index(keys=[("name", pymongo.DESCENDING)], unique=True) # 查询索引 result = sorted(list(collection.index_information())) print(result)
- 文書の変更
from pymongo import MongoClient
connect = MongoClient(host='localhost', port=27017, username="root", password="123456",) # 获取db test_db = connect['test'] # 获取collection collection = test_db['students'] result = collection.update({'name': 'robby'}, {'$set': {"name": "Petter"}}) print(result) 注意:还有update_many()方法
- 文書の削除
from pymongo import MongoClient
connect = MongoClient(host='localhost', port=27017, username="root", password="123456",) # 获取db test_db = connect['test'] # 获取collection collection = test_db['students'] result = collection.delete_one({'name': 'Petter'}) print(result.deleted_count) 注意:还有delete_many()方法
4.MongoDB ODM詳細
- DjangoのORMに類似の方法を使用して、MongoDBのODM。
- MongoEngineマッパーは、Python、処理のためにMongoDBに書き込まれた対象文書です。
- 抽象MongoEngineは、すべてのモデルが作成されるように、クラスベースで提供します。
# 安装mongoengine
pip install mongoengine
- mongoengineを使用したタイプのフィールド
BinaryField
BooleanField
ComplexDateTimeField
DateTimeField
DecimalField
DictField
DynamicField
EmailField
EmbeddedDocumentField
EmbeddedDocumentListField
FileField
FloatField
GenericEmbeddedDocumentField
GenericReferenceField
GenericLazyReferenceField
GeoPointField
ImageField
IntField
ListField:可以将自定义的文档类型嵌套
MapField
ObjectIdField
ReferenceField
LazyReferenceField
SequenceField
SortedListField
StringField
URLField
UUIDField
PointField
LineStringField
PolygonField
MultiPointField
MultiLineStringField
MultiPolygonField
5. mongoengineを使用してデータベース接続を作成します。
from mongoengine import connect
conn = connect(db='test', host='localhost', port=27017, username='root', password='123456', authentication_source='admin')
print(conn)
connect(db = None,alias ='default',** kwargs );
db
:接続との互換性のために使用されるデータベースの名前。host
:ホスト名は、接続したいインスタンスをmongodは、port
:ポートのmongodインスタンスを実行します。username
:ユーザー名を認証するために使用します。password
:パスワード認証の場合。authentication_source
:データベースを認証するには、
モデル文書の構築、挿入データ
from mongoengine import connect, \
Document, \
StringField,\
IntField, \ FloatField,\ ListField, \ EmbeddedDocumentField,\ DateTimeField, \ EmbeddedDocument from datetime import datetime # 嵌套文档 class Score(EmbeddedDocument): name = StringField(max_length=50, required=True) value = FloatField(required=True) class Students(Document): choice = (('F', 'female'), ('M', 'male'),) name = StringField(max_length=100, required=True, unique=True) age = IntField(required=True) hobby = StringField(max_length=100, required=True, ) gender = StringField(choices=choice, required=True) # 这里使用到了嵌套文档,这个列表中的每一个元素都是一个字典,因此使用嵌套类型的字段 score = ListField(EmbeddedDocumentField(Score)) time = DateTimeField(default=datetime.now()) if __name__ == '__main__': connect(db='test', host='localhost', port=27017, username='root', password='123456', authentication_source='admin') math_score = Score(name='math', value=94) chinese_score = Score(name='chinese', value=100) python_score = Score(name='python', value=99) for i in range(10): students = Students(name='robby{}'.format(i), age=int('{}'.format(i)), hobby='read', gender='M', score=[math_score, chinese_score, python_score]) students.save()
クエリデータ
from mongoengine import connect, \
Document, \
StringField,\
IntField, \
FloatField,\
ListField, \
EmbeddedDocumentField,\
DateTimeField, \
EmbeddedDocument
from datetime import datetime
# 嵌套文档 class Score(EmbeddedDocument): name = StringField(max_length=50, required=True) value = FloatField(required=True) class Students(Document): choice = (('F', 'female'), ('M', 'male'),) name = StringField(max_length=100, required=True, unique=True) age = IntField(required=True) hobby = StringField(max_length=100, required=True, ) gender = StringField(choices=choice, required=True) # 这里使用到了嵌套文档,这个列表中的每一个元素都是一个字典,因此使用嵌套类型的字段 score = ListField(EmbeddedDocumentField(Score)) time = DateTimeField(default=datetime.now()) if __name__ == '__main__': connect(db='test', host='localhost', port=27017, username='root', password='123456', authentication_source='admin') first_document = Students.objects.first() all_document = Students.objects.all() # 如果只有一条,也可以使用get specific_document = Students.objects.filter(name='robby3') print(first_document.name, first_document.age, first_document.time) for document in all_document: print(document.name) for document in specific_document: print(document.name, document.age)
変更、更新、データを削除
from mongoengine import connect, \
Document, \
StringField,\
IntField, \ FloatField,\ ListField, \ EmbeddedDocumentField,\ DateTimeField, \ EmbeddedDocument from datetime import datetime # 嵌套文档 class Score(EmbeddedDocument): name = StringField(max_length=50, required=True) value = FloatField(required=True) class Students(Document): choice = (('F', 'female'), ('M', 'male'),) name = StringField(max_length=100, required=True, unique=True) age = IntField(required=True) hobby = StringField(max_length=100, required=True, ) gender = StringField(choices=choice, required=True) # 这里使用到了嵌套文档,这个列表中的每一个元素都是一个字典,因此使用嵌套类型的字段 score = ListField(EmbeddedDocumentField(Score)) time = DateTimeField(default=datetime.now()) if __name__ == '__main__': connect(db='test', host='localhost', port=27017, username='root', password='123456', authentication_source='admin') specific_document = Students.objects.filter(name='robby3') specific_document.update(set__age=100) specific_document.update_one(set__age=100) for document in specific_document: document.name = 'ROBBY100' document.save() for document in specific_document: document.delete()
all()
:すべての文書を返します。all_fields()
:すべてのフィールドが含まれています。as_pymongo()
:ドキュメントのインスタンスが、pymongo値を返されません。average()
:平均値は、フィールドの特定の値を超えます。batch_size()
:単一のバッチで返されるドキュメントの数を制限します。clone()
:現在のクエリセットのコピーを作成します。comment()
:クエリにコメントを追加します。count()
:クエリで選択された要素を計算します。create()
:新しいオブジェクトを作成し、オブジェクトのインスタンスを保存するために戻ります。delete()
:クエリ照合文書を削除します。distinct()
:フィールド値の異なるリストを返します。
埋め込まれた文書のクエリメソッド
count()
:リスト、リストの長さが埋め込まれた文書の数。create()
:新しい埋め込まれた文書を作成し、それをデータベースに保存します。delete()
:文書に埋め込まれたデータベースから削除します。exclude(** kwargs )
:埋め込まれた文書を除外するために与えられたキーワード引数を使用して、リストをフィルタリングするには、first()
:最初に埋め込まれた文書に戻ります。get()
:指定されたキーワード引数によって決定埋め込み文書検索。save()
:先祖の文書を保存します。update()
:埋め込まれた文書を更新した値を交換します。