Python中怎么操作MongoDB文檔數(shù)據(jù)庫(kù),相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。

安裝pymongo: pip install pymongo
PyMongo是驅(qū)動(dòng)程序,使python程序能夠使用Mongodb數(shù)據(jù)庫(kù),使用python編寫而成;
insert_one():插入一條記錄;
insert():插入多條記錄;
find_one():查詢一條記錄,不帶任何參數(shù)返回第一條記錄,帶參數(shù)則按條件查找返回;
find():查詢多條記錄,不帶參數(shù)返回所有記錄,帶參數(shù)按條件查找返回;
count():查看記錄總數(shù);
create_index():創(chuàng)建索引;
update_one():更新匹配到的第一條數(shù)據(jù);
update():更新匹配到的所有數(shù)據(jù);
remove():刪除記錄,不帶參表示刪除全部記錄,帶參則表示按條件刪除;
delete_one():刪除單條記錄;
delete_many():刪除多條記錄;
查看數(shù)據(jù)庫(kù)
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())獲取數(shù)據(jù)庫(kù)實(shí)例
test_db = connect['test']
獲取collection實(shí)例
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']
# 構(gòu)建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)
# 通過(guò)條件過(guò)濾出一條document
one_result = collection.find_one({"author": "Mike"})
# 解析document字段
print(one_result, type(one_result))
print(one_result['_id'])
print(one_result['author'])
注意:如果需要通過(guò)id查詢一行document,需要將id包裝為ObjectId類的實(shí)例對(duì)象
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)
# 通過(guò)條件過(guò)濾出多條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']
# 通過(guò)條件過(guò)濾時(shí)間小于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)創(chuàng)建索引
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']
# 創(chuàng)建字段索引
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是一個(gè)對(duì)象文檔映射器,用Python編寫,用于處理MongoDB;
MongoEngine提供的抽象是基于類的,創(chuàng)建的所有模型都是類;
# 安裝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:要使用的數(shù)據(jù)庫(kù)的名稱,以便與connect兼容;
host
:要連接的mongod實(shí)例的主機(jī)名;
port
:運(yùn)行mongod實(shí)例的端口;
username:用于進(jìn)行身份驗(yàn)證的用戶名;
password:用于進(jìn)行身份驗(yàn)證的密碼;
authentication_source
:要進(jìn)行身份驗(yàn)證的數(shù)據(jù)庫(kù);
構(gòu)建文檔模型,插入數(shù)據(jù)
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)
# 這里使用到了嵌套文檔,這個(gè)列表中的每一個(gè)元素都是一個(gè)字典,因此使用嵌套類型的字段
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()查詢數(shù)據(jù)
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)
# 這里使用到了嵌套文檔,這個(gè)列表中的每一個(gè)元素都是一個(gè)字典,因此使用嵌套類型的字段
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)修改、更新、刪除數(shù)據(jù)
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)
# 這里使用到了嵌套文檔,這個(gè)列表中的每一個(gè)元素都是一個(gè)字典,因此使用嵌套類型的字段
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實(shí)例 而是pymongo值;
average():平均值超過(guò)指定字段的值;
batch_size():限制單個(gè)批次中返回的文檔數(shù)量;
clone():創(chuàng)建當(dāng)前查詢集的副本;
comment():在查詢中添加注釋;
count():計(jì)算查詢中的選定元素;
create():創(chuàng)建新對(duì)象,返回保存的對(duì)象實(shí)例;
delete():刪除查詢匹配的文檔;
distinct():返回給定字段的不同值列表;
count():列表中嵌入文檔的數(shù)量,列表的長(zhǎng)度;
create():創(chuàng)建新的嵌入式文檔并將其保存到數(shù)據(jù)庫(kù)中;
delete():從數(shù)據(jù)庫(kù)中刪除嵌入的文檔;
exclude(** kwargs ):通過(guò)使用給定的關(guān)鍵字參數(shù)排除嵌入的文檔來(lái)過(guò)濾列表;
first():返回列表中的第一個(gè)嵌入文檔;
get():檢索由給定關(guān)鍵字參數(shù)確定的嵌入文檔;
save():保存祖先文檔;
update():使用給定的替換值更新嵌入的文檔;
看完上述內(nèi)容,你們掌握Python中怎么操作MongoDB文檔數(shù)據(jù)庫(kù)的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司行業(yè)資訊頻道,感謝各位的閱讀!
網(wǎng)站名稱:Python中怎么操作MongoDB文檔數(shù)據(jù)庫(kù)-創(chuàng)新互聯(lián)
文章出自:http://www.chinadenli.net/article6/igoog.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供建站公司、網(wǎng)站策劃、網(wǎng)站收錄、網(wǎng)站營(yíng)銷、全網(wǎng)營(yíng)銷推廣、微信小程序
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)