您好,登錄后才能下訂單哦!
Python中怎么操作MongoDB文檔數據庫,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
安裝pymongo: pip install pymongo
PyMongo是驅動程序,使python程序能夠使用Mongodb數據庫,使用python編寫而成;
insert_one()
:插入一條記錄;
insert()
:插入多條記錄;
find_one()
:查詢一條記錄,不帶任何參數返回第一條記錄,帶參數則按條件查找返回;
find()
:查詢多條記錄,不帶參數返回所有記錄,帶參數按條件查找返回;
count()
:查看記錄總數;
create_index()
:創建索引;
update_one()
:更新匹配到的第一條數據;
update()
:更新匹配到的所有數據;
remove()
:刪除記錄,不帶參表示刪除全部記錄,帶參則表示按條件刪除;
delete_one()
:刪除單條記錄;
delete_many()
:刪除多條記錄;
查看數據庫
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實例
collection = test_db['students']
插入一行document, 查詢一行document,取出一行document的值
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')})
插入多行documents, 查詢多行document, 查看collections有多少行document
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)
document修改
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()方法
document刪除
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()方法
MongoDB ODM 與 Django ORM使用方法類似;
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
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
:要使用的數據庫的名稱,以便與connect兼容;
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()
:返回的不是Document實例 而是pymongo值;
average()
:平均值超過指定字段的值;
batch_size()
:限制單個批次中返回的文檔數量;
clone()
:創建當前查詢集的副本;
comment()
:在查詢中添加注釋;
count()
:計算查詢中的選定元素;
create()
:創建新對象,返回保存的對象實例;
delete()
:刪除查詢匹配的文檔;
distinct()
:返回給定字段的不同值列表;
count()
:列表中嵌入文檔的數量,列表的長度;
create()
:創建新的嵌入式文檔并將其保存到數據庫中;
delete()
:從數據庫中刪除嵌入的文檔;
exclude(** kwargs )
:通過使用給定的關鍵字參數排除嵌入的文檔來過濾列表;
first()
:返回列表中的第一個嵌入文檔;
get()
:檢索由給定關鍵字參數確定的嵌入文檔;
save()
:保存祖先文檔;
update()
:使用給定的替換值更新嵌入的文檔;
看完上述內容,你們掌握Python中怎么操作MongoDB文檔數據庫的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。