PyMongo是驅動程式,使python程式能夠使用Mongodb資料庫,使用python編寫而成 ...
1.Pymongo 安裝
安裝pymongo:
pip install pymongo
- PyMongo是驅動程式,使python程式能夠使用Mongodb資料庫,使用python編寫而成;
2.Pymongo 方法
insert_one()
:插入一條記錄;insert()
:插入多條記錄;find_one()
:查詢一條記錄,不帶任何參數返回第一條記錄,帶參數則按條件查找返回;find()
:查詢多條記錄,不帶參數返回所有記錄,帶參數按條件查找返回;count()
:查看記錄總數;create_index()
:創建索引;update_one()
:更新匹配到的第一條數據;update()
:更新匹配到的所有數據;remove()
:刪除記錄,不帶參表示刪除全部記錄,帶參則表示按條件刪除;delete_one()
:刪除單條記錄;delete_many()
:刪除多條記錄;
3.Pymongo 中的操作
- 查看資料庫
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()方法
4.MongoDB ODM 詳解
- 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
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
:要使用的資料庫的名稱,以便與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()
:使用給定的替換值更新嵌入的文檔;