欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

如何用python 操作MongoDB數(shù)據(jù)庫

 更新時間:2021年04月16日 15:02:43   作者:三只松鼠  
這篇文章主要介紹了如何用python 操作MongoDB數(shù)據(jù)庫,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下

一、前言

  MongoDB屬于 NoSQL(非關(guān)系型數(shù)據(jù)庫),是一個基于分布式文件存儲的開源數(shù)據(jù)庫系統(tǒng)。

二、操作 MongoDB

1、安裝 pymongo

python 使用第三方庫來連接操作 MongoDB,所以我們首先安裝此庫。

pip3 install pymongodb

2、連接 MongoDB

使用 MongoClient 類連接,以下兩種參數(shù)方式都可以:

from pymongo import MongoClient

# 連接方式一
client = MongoClient(host='localhost',port=27017)
# 連接方式二
# client = MongoClient('mongodb://localhost:27017/')

3、選擇數(shù)據(jù)庫

MongoDB 可以創(chuàng)建很多 db,指定我們需要的 db 即可

# 方式一
db = client.Monitor
# 方式二
# db = client['Monitor']

4、選擇集合

db 內(nèi)包含很多個集合,有點類似 mysql 這類關(guān)系型數(shù)據(jù)庫中的表

# 方式一
collection = db.test
# 方式二
# collection = db['test']

5、插入數(shù)據(jù)

插入一條數(shù)據(jù),MongoDB 每條記錄都有一個唯一標識。返回一個 InsertOneResult 對象,若需要獲取唯一標識,找到 InsertOneResult 對象的屬性 inserted_id 即可

from pymongo import MongoClient

class mongodb:
    def __init__(self,host,db,port = 27017):
        '''
        :param host: str mongodb地址
        :param db: str 數(shù)據(jù)庫
        :param port: int 端口,默認為27017
        '''
        host = host
        db = db
        self.port = port
        client = MongoClient(host=host,port=port)
        self.db = client[db]

    def insert_one(self,table,dic):
        '''
        :param table: str 數(shù)據(jù)庫中的集合
        :param dic: dict 要插入的字典
        :return: 返回一個包含ObjectId類型的對象
        '''
        collection = self.db[table]
        rep = collection.insert_one(dic)

        return repif __name__=='__main__':
    dic = {'姓名':'小明','English':100,'math':90}
    db = mongodb(host='localhost',db = 'test')
    rep = db.insert_one('test',dic)
    print(rep.inserted_id)

插入多條數(shù)據(jù),使用 insert_many 批量插入

from pymongo import MongoClient

class mongodb:
    def __init__(self,host,db,port = 27017):
        '''
        :param host: str mongodb地址
        :param db: str 數(shù)據(jù)庫
        :param port: int 端口,默認為27017
        '''
        host = host
        db = db
        self.port = port
        client = MongoClient(host=host,port=port)
        self.db = client[db]

    def insert_one(self,table,dic):
        '''
        :param table: str 數(shù)據(jù)庫中的集合
        :param dic: dict 要插入的字典
        :return: 返回包含一個ObjectId類型的對象
        '''
        collection = self.db[table]
        rep = collection.insert_one(dic)

        return rep

    def insert_many(self,table,lists):
        '''
        :param table: str 數(shù)據(jù)庫中的集合
        :param dic: dict 要插入的列表,列表中的元素為字典
        :return: 返回包含多個ObjectId類型的列表對象
        '''
        collection = self.db[table]
        rep = collection.insert_many(lists)

        return rep


if __name__=='__main__':
    lists = [{'姓名':'小明','English':100,'math':90},
             {'姓名':'小華','English':90,'math':100}]
    db = mongodb(host='localhost',db = 'test')
    rep = db.insert_many('test',lists)
    for i in rep.inserted_ids:
        print(i)

6、查詢

1)常規(guī)查詢

  •  find_one :查詢單條記錄,返回一個字典。
  •  find:查詢多條記錄 ,返回一個游標對象。
from pymongo import MongoClient

class mongodb:
    def __init__(self,host,db,port = 27017):
        '''
        :param host: str mongodb地址
        :param db: str 數(shù)據(jù)庫
        :param port: int 端口,默認為27017
        '''
        host = host
        db = db
        self.port = port
        client = MongoClient(host=host,port=port)
        self.db = client[db]

    def find_one(self,table,dic):
        '''
        :param table: str 數(shù)據(jù)庫中的集合
        :param dic: dict 查詢條件
        :return: dict 返回單條記錄的字典
        '''
        collection = self.db[table]
        rep = collection.find_one(dic)

        return rep

    def find(self,table,dic):
        '''
        :param table: str 數(shù)據(jù)庫中的集合
        :param dic: dict 查詢條件
        :return: list 返回查詢到記錄的列表
        '''
        collection = self.db[table]
        rep = list(collection.find(dic))

        return rep

if __name__=='__main__':
    # 查詢 English 成績?yōu)?100 的所有記錄
    dic = {'English':100}
    db = mongodb(host='localhost',db = 'test')
    rep = db.insert_many('test',dic)
    print(rep)

2)范圍查詢

有時候我們需要范圍比較查詢,比如要查詢 English 成績?yōu)?80~90 ,可以使用比較符:dic = {'English':{'$in':[80,90]}}

  • $lt :小于
  • $lte:小于等于
  • $gt:大于
  • $gte:大于等于
  • $ne:不等于
  • $in:在范圍內(nèi)
  • $nin:不在范圍內(nèi) 

3)計數(shù)

直接調(diào)用 count() 方法,返回一個 int 類型的數(shù)字

# 計數(shù)查詢只需要在普通查詢后加上 count() 即可
count = collection.find().count()  
# count = collection.find({'English':{'$gt':90}}).count()

4)排序

排序時,直接調(diào)用sort()方法,并在其中傳入排序的字段及升降序標志,返回一個游標對象

# 正序 ASCENDING,倒序 DESCENDING。list()將游標對象轉(zhuǎn)成列表
data = list(collection.find(dic).sort('姓名',pymongo.DESCENDING))

7、更新數(shù)據(jù)

首選查到需要更新的數(shù)據(jù),然后將該數(shù)據(jù)更新,返回一個 UpdataResult 對象, raw_result 屬性中包含 update 生效的個數(shù)。

  • update_one:更新查詢到的第一條數(shù)據(jù)
  • update_many:更新多條數(shù)據(jù)
from pymongo import MongoClient

class mongodb:
    def __init__(self,host,db,port = 27017):
        '''
        :param host: str mongodb地址
        :param db: str 數(shù)據(jù)庫
        :param port: int 端口,默認為27017
        '''
        host = host
        db = db
        self.port = port
        client = MongoClient(host=host,port=port)
        self.db = client[db]

    def update_one(self,table,condition,dic):
        '''
        :param table: str 數(shù)據(jù)庫中的集合
        :param condition: dict 查詢條件
        :param dic: dict 更新的數(shù)據(jù)
        :return: 返回UpdateResult對象
        '''
        collection = self.db[table]
        # $set 表示只更新dic字典內(nèi)存在的字段
        rep = collection.update_one(condition,{'$set':dic})
        # 會把之前的數(shù)據(jù)全部用dic字典替換,如果原本存在其他字段,則會被刪除
        # rep = collection.update_one(condition, dic)

        return rep

    def update_many(self,table,condition,dic):
        '''
        :param table: str 數(shù)據(jù)庫中的集合
        :param condition: dict 查詢條件
        :param dic: dict 更新的數(shù)據(jù)
        :return:返回UpdateResult對象
        '''
        collection = self.db[table]
        # $set 表示只更新dic字典內(nèi)存在的字段
        rep = collection.update_many(condition,{'$set':dic})
        # 會把之前的數(shù)據(jù)全部用dic字典替換,如果原本存在其他字段,則會被刪除
        # rep = collection.update_many(condition, dic)

        return rep


if __name__=='__main__':
    condition = {'English':80}
    dic = {'English':60}
    db = mongodb(host='mongodb-monitor.monitor.svc.test.local',db = 'test')
    rep = db.update_one('test',condition,dic)
    print(rep.raw_result)
    # 輸出 {'n': 1, 'nModified': 1, 'ok': 1.0, 'updatedExisting': True}

8、刪除

刪除和 update 類似,刪除數(shù)據(jù)后,返回一個 DeleteResult 對象, raw_result 屬性中包含 delete 的個數(shù)

  • delete_one:刪除查詢到的第一條數(shù)據(jù)
  • delete_many:批量刪除符合查詢條件的數(shù)據(jù)
from pymongo import MongoClient

class mongodb:
    def __init__(self,host,db,port = 27017):
        '''
        :param host: str mongodb地址
        :param db: str 數(shù)據(jù)庫
        :param port: int 端口,默認為27017
        '''
        host = host
        db = db
        self.port = port
        client = MongoClient(host=host,port=port)
        self.db = client[db]

    def delete_one(self,table,dic):
        '''
        :param table: str 數(shù)據(jù)庫中的集合
        :param dic: dict 查詢條件
        :return: 返回DeleteResult對象
        '''
        collection = self.db[table]
        rep = collection.delete_one(dic)

        return rep

    def delete_many(self,table,dic):
        '''
        :param table: str 數(shù)據(jù)庫中的集合
        :param dic: dict 查詢條件
        :return: 返回DeleteResult對象
        '''
        collection = self.db[table]
        rep = collection.delete_many(dic)

        return rep


if __name__=='__main__':
    dic = {'English':60}
    db = mongodb(host='localhost',db = 'test')
    rep = db.delete_many('test',dic)
    print(rep.raw_result)
    # 輸出 {'n': 21, 'ok': 1.0}

以上就是如何用python 操作MongoDB數(shù)據(jù)庫的詳細內(nèi)容,更多關(guān)于python 操作MongoDB數(shù)據(jù)庫的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • python gdal安裝與簡單使用

    python gdal安裝與簡單使用

    這篇文章主要介紹了python gdal安裝與簡單使用,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-08-08
  • python3 使用函數(shù)求兩個數(shù)的和與差

    python3 使用函數(shù)求兩個數(shù)的和與差

    這篇文章主要介紹了python3 使用函數(shù)求兩個數(shù)的和與差,具有很好的參考價值,希望對大家有所幫助。
    2021-05-05
  • 基于Python實現(xiàn)模擬三體運動的示例代碼

    基于Python實現(xiàn)模擬三體運動的示例代碼

    此前所做的一切三體和太陽系的動畫,都是基于牛頓力學(xué)的,而且直接對微分進行差分化,從而精度非常感人,用不了幾年就得撞一起去。所以本文來用Python重新模擬一下三體運動,感興趣的可以了解一下
    2023-03-03
  • Python從文件中讀取數(shù)據(jù)的方法步驟

    Python從文件中讀取數(shù)據(jù)的方法步驟

    這篇文章主要介紹了Python從文件中讀取數(shù)據(jù)的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • 基于Python爬取fofa網(wǎng)頁端數(shù)據(jù)過程解析

    基于Python爬取fofa網(wǎng)頁端數(shù)據(jù)過程解析

    這篇文章主要介紹了基于Python爬取fofa網(wǎng)頁端數(shù)據(jù)過程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-07-07
  • Pytorch模型定義與深度學(xué)習(xí)自查手冊

    Pytorch模型定義與深度學(xué)習(xí)自查手冊

    這篇文章主要為大家介紹了Pytorch模型定義與深度學(xué)習(xí)的自查手冊,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-06-06
  • Python簡潔優(yōu)雅的推導(dǎo)式示例詳解

    Python簡潔優(yōu)雅的推導(dǎo)式示例詳解

    這篇文章主要給大家介紹了關(guān)于Python簡潔優(yōu)雅的推導(dǎo)式的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • 詳解C++編程中一元運算符的重載

    詳解C++編程中一元運算符的重載

    這篇文章主要介紹了C++編程中一元運算符的重載,特別對遞增和遞減運算符重載作了著重講解,需要的朋友可以參考下
    2016-01-01
  • Python3中小括號()、中括號[]、花括號{}的區(qū)別詳解

    Python3中小括號()、中括號[]、花括號{}的區(qū)別詳解

    這篇文章主要介紹了Python3中小括號()、中括號[]、花括號{}的區(qū)別詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • 用python找出那些被“標記”的照片

    用python找出那些被“標記”的照片

    這篇文章主要介紹了用python找出那些被“標記”的照片的相關(guān)資料,需要的朋友可以參考下
    2017-04-04

最新評論