Python操作MongoDB文件資料庫

Winter發表於2019-05-09

1.Pymongo 安裝


安裝pymongo:
pip install pymongo

  • PyMongo是驅動程式,使python程式能夠使用Mongodb資料庫,使用python編寫而成;

2.Pymongo 方法

  • one_insert() :插入一條記錄;

  • 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() :使用給定的替換值更新嵌入的文件;

參考: https://www.9xkd.com/user/plan-view.html?id=2253255600

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69908432/viewspace-2643763/,如需轉載,請註明出處,否則將追究法律責任。

相關文章