日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python mongodb_Python操作MongoDB文档数据库

發布時間:2023/12/8 python 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python mongodb_Python操作MongoDB文档数据库 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

總結

以上是生活随笔為你收集整理的python mongodb_Python操作MongoDB文档数据库的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。