Detailed explanation of Python operation MongoDB

Hi everyone, hello! I am cheese ❤

insert image description here

I. Introduction

MongoDB belongs to NoSQL (non-relational database) and
is an open source database system based on distributed file storage.

Two, operate MongoDB

1. Install pymongo

Python uses a third-party library to connect and operate MongoDB,
so we install this library first.

pip3 install pymongodb

2. Connect to MongoDB

Use the MongoClient class connection,
the following two parameter methods are available:

from pymongo import MongoClient

# 连接方式一
client = MongoClient(host='localhost',port=27017)
# 连接方式二
# client = MongoClient('mongodb://localhost:27017/学习资料无偿领扣扣qun:540305994')

3. Select the database

MongoDB can create many db,
just specify the db we need

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

4. Select Collection

db contains many collections, which
is a bit similar to the tables in relational databases such as mysql

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

5. Insert data

To insert a piece of data,
each MongoDB record has a unique identifier.
Return an InsertOneResult object,
if you need to obtain a unique identifier,
just find the inserted_id attribute of the InsertOneResult object

from pymongo import MongoClient

class mongodb:
    def __init__(self,host,db,port = 27017):
        '''
        :param host: str mongodb地址
        :param db: str 数据库
        :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 数据库中的集合
        :param dic: dict 要插入的字典
        :return: 返回一个包含ObjectId类型的对象
        '''
        collection = self.db[table]
        rep = collection.insert_one(dic)

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

Insert multiple pieces of data, use insert_many to insert in batches

from pymongo import MongoClient

class mongodb:
    def __init__(self,host,db,port = 27017):
        '''
        :param host: str mongodb地址
        :param db: str 数据库
        :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 数据库中的集合
        :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 数据库中的集合
        :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. Query

1) General query

  • find_one : Query a single record and return a dictionary.
  • find: Query multiple records and return a cursor object.
from pymongo import MongoClient

class mongodb:
    def __init__(self,host,db,port = 27017):
        '''
        :param host: str mongodb地址
        :param db: str 数据库
        :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 数据库中的集合
        :param dic: dict 查询条件
        :return: dict 返回单条记录的字典
        '''
        collection = self.db[table]
        rep = collection.find_one(dic)

        return rep

    def find(self,table,dic):
        '''
        :param table: str 数据库中的集合
        :param dic: dict 查询条件
        :return: list 返回查询到记录的列表
        '''
        collection = self.db[table]
        rep = list(collection.find(dic))

        return rep

if __name__=='__main__':
    # 查询 English 成绩为 100 的所有记录
    dic = {
    
    'English':100}
    db = mongodb(host='localhost',db = 'test')
    rep = db.find('test',dic)
    print(rep)

2) range query

Sometimes we need range comparison queries.
For example, to query English scores of 80~90,
you can use the comparator:dic = {'English':{'$in':[80,90]}}

  • $lt : less than
  • $lte: less than or equal to
  • $gt: greater than
  • $gte: greater than or equal to
  • $ne: not equal to
  • $in: in scope
  • $nin: not in range

3) Fuzzy query

If you want to query like this sql statement:
select * from db where name like '%abc%'
it can be realized by regular expression in MongoDB

# 模糊搜索key为"姓名",value包含"明"的记录
dic = {
    
    '姓名':{
    
    '$regex':'明'}}
rep = list(collection.find(dic))

4) Field screening

If you only want to return the specified field, add the projection parameter when using the find (find_one) method. Similar to SQL syntax: select Englist from db where name like '%abc%'

# projection字典参数。1显示,0不显示
# 以下查询结果只返回key为English的相关字段
rep = list(collection.find(dic,projection={
    
    'English':1,'_id':0}))

5) count

Call the count() method directly to return a number of type int

# 计数查询只需要在普通查询后加上 count() 即可
count = collection.find().count()  
# count = collection.find({'English':{'$gt':90}}).count()

6) Sort

排序时,直接调用sort()方法,并在其中传入排序的字段及升降序标志,返回一个游标对象

# 正序 ASCENDING,倒序 DESCENDING。list()将游标对象转成列表
data = list(collection.find(dic).sort('姓名',pymongo.DESCENDING))

7. Update data

The first choice is to find the data that needs to be updated, then update the data, and return an UpdataResult object, and the raw_result attribute contains the number of updates that take effect.

  • update_one: update the first piece of data queried
  • update_many: update multiple pieces of data
from pymongo import MongoClient

class mongodb:
    def __init__(self,host,db,port = 27017):
        '''
        :param host: str mongodb地址
        :param db: str 数据库
        :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 数据库中的集合
        :param condition: dict 查询条件
        :param dic: dict 更新的数据
        :return: 返回UpdateResult对象
        '''
        collection = self.db[table]
        # $set 表示只更新dic字典内存在的字段
        rep = collection.update_one(condition,{
    
    '$set':dic})
        # 会把之前的数据全部用dic字典替换,如果原本存在其他字段,则会被删除
        # rep = collection.update_one(condition, dic)

        return rep

    def update_many(self,table,condition,dic):
        '''
        :param table: str 数据库中的集合
        :param condition: dict 查询条件
        :param dic: dict 更新的数据
        :return:返回UpdateResult对象
        '''
        collection = self.db[table]
        # $set 表示只更新dic字典内存在的字段
        rep = collection.update_many(condition,{
    
    '$set':dic})
        # 会把之前的数据全部用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. Delete

Delete is similar to update. After deleting data, a DeleteResult object is returned. The raw_result attribute contains the number of deletes

  • delete_one: delete the first piece of data queried
  • delete_many: Delete data that meets the query conditions in batches
from pymongo import MongoClient

class mongodb:
    def __init__(self,host,db,port = 27017):
        '''
        :param host: str mongodb地址
        :param db: str 数据库
        :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 数据库中的集合
        :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 数据库中的集合
        :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}

That's it for today's article~

See you in the next article (✿◡‿◡)

insert image description here

Guess you like

Origin blog.csdn.net/m0_74872863/article/details/130012414