How to operate MongoDB database with python

  • 2021-10-27 08:06:03
  • OfStack

Catalogue 1. Preface
2. Operate MongoDB
1. Install pymongo
2. Connect MongoDB
3. Select the database
4. Select the set
5. Insert data
6. Inquiry
7. Update the data
8. Delete

1. Preface

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

2. Operate MongoDB

1. Install pymongo

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

pip3 install pymongodb

2. Connect MongoDB

Using the MongoClient class connection, the following two parameter methods can be used:


from pymongo import MongoClient

#  Connection mode 1
client = MongoClient(host='localhost',port=27017)
#  Connection mode 2
# client = MongoClient('mongodb://localhost:27017/')

3. Select the database

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


#  Mode 1
db = client.Monitor
#  Mode 2
# db = client['Monitor']

4. Select the set

db contains many collections, somewhat like tables in relational databases such as mysql


#  Mode 1
collection = db.test
#  Mode 2
# collection = db['test']

5. Insert data

Insert one piece of data, and each record in MongoDB has one only one identity. Returns 1 InsertOneResult object. If you need to get only 1 ID, you can find the attribute inserted_id of InsertOneResult object


from pymongo import MongoClient

class mongodb:
    def __init__(self,host,db,port = 27017):
        '''
        :param host: str mongodb Address 
        :param db: str  Database 
        :param port: int  Port, default to 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  Collections in a database 
        :param dic: dict  Dictionary to insert 
        :return:  Return 1 Contains ObjectId Objects of type 
        '''
        collection = self.db[table]
        rep = collection.insert_one(dic)

        return repif __name__=='__main__':
    dic = {' Name ':' Xiao Ming ','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, batch insert using insert_many


from pymongo import MongoClient

class mongodb:
    def __init__(self,host,db,port = 27017):
        '''
        :param host: str mongodb Address 
        :param db: str  Database 
        :param port: int  Port, default to 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  Collections in a database 
        :param dic: dict  Dictionary to insert 
        :return:  Returns the containing 1 A ObjectId Objects of type 
        '''
        collection = self.db[table]
        rep = collection.insert_one(dic)

        return rep

    def insert_many(self,table,lists):
        '''
        :param table: str  Collections in a database 
        :param dic: dict  The list to insert, the element in the list is a dictionary 
        :return:  Returns a file containing more than one ObjectId List object of type 
        '''
        collection = self.db[table]
        rep = collection.insert_many(lists)

        return rep


if __name__=='__main__':
    lists = [{' Name ':' Xiao Ming ','English':100,'math':90},
             {' Name ':' Xiaohua ','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. Inquiry

1) General query

find_one: Query a single record and return a dictionary. find: Query multiple records and return 1 cursor object.

from pymongo import MongoClient

class mongodb:
    def __init__(self,host,db,port = 27017):
        '''
        :param host: str mongodb Address 
        :param db: str  Database 
        :param port: int  Port, default to 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  Collections in a database 
        :param dic: dict  Query criteria 
        :return: dict  Returns a dictionary for a single record 
        '''
        collection = self.db[table]
        rep = collection.find_one(dic)

        return rep

    def find(self,table,dic):
        '''
        :param table: str  Collections in a database 
        :param dic: dict  Query criteria 
        :return: list  Returns a list of queried records 
        '''
        collection = self.db[table]
        rep = list(collection.find(dic))

        return rep

if __name__=='__main__':
    #  Query  English  The result is  100  All records of 
    dic = {'English':100}
    db = mongodb(host='localhost',db = 'test')
    rep = db.insert_many('test',dic)
    print(rep)

2) Scope query

Sometimes we need range comparison queries, for example, to query English scores of 80 ~ 90, we can use the comparison symbol: 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 range $nin: Out of range

3) Counting

Call the count () method directly and return 1 number of type int


#  The count query only needs to be added after the ordinary query  count()  You can 
count = collection.find().count()  
# count = collection.find({'English':{'$gt':90}}).count()

4) Sort

When sorting, call sort () method directly, and pass in the sorted field and ascending and descending order flag, and return 1 cursor object


#  Positive order  ASCENDING Reverse order  DESCENDING . list() Convert cursor objects to lists 
data = list(collection.find(dic).sort(' Name ',pymongo.DESCENDING))

7. Update the data

It is preferred to find the data to be updated, and then update the data to return 1 UpdataResult object, and the raw_result attribute contains the number of update effective.

update_one: Update the first 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 Address 
        :param db: str  Database 
        :param port: int  Port, default to 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  Collections in a database 
        :param condition: dict  Query criteria 
        :param dic: dict  Updated data 
        :return:  Return UpdateResult Object 
        '''
        collection = self.db[table]
        # $set  Indicates that only updates dic Fields existing in the dictionary 
        rep = collection.update_one(condition,{'$set':dic})
        #  Will use all the previous data dic Dictionary replacement, if there are other fields, they will be deleted 
        # rep = collection.update_one(condition, dic)

        return rep

    def update_many(self,table,condition,dic):
        '''
        :param table: str  Collections in a database 
        :param condition: dict  Query criteria 
        :param dic: dict  Updated data 
        :return: Return UpdateResult Object 
        '''
        collection = self.db[table]
        # $set  Indicates that only updates dic Fields existing in the dictionary 
        rep = collection.update_many(condition,{'$set':dic})
        #  Will use all the previous data dic Dictionary replacement, if there are other fields, they will be deleted 
        # 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)
    #  Output  {'n': 1, 'nModified': 1, 'ok': 1.0, 'updatedExisting': True}

8. Delete

Deletion is similar to update. After deleting data, 1 DeleteResult object is returned, and the number of delete is contained in the raw_result attribute

delete_one: Delete the first item of data queried delete_many: Batch Delete Data Matching Query Criteria

from pymongo import MongoClient

class mongodb:
    def __init__(self,host,db,port = 27017):
        '''
        :param host: str mongodb Address 
        :param db: str  Database 
        :param port: int  Port, default to 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  Collections in a database 
        :param dic: dict  Query criteria 
        :return:  Return DeleteResult Object 
        '''
        collection = self.db[table]
        rep = collection.delete_one(dic)

        return rep

    def delete_many(self,table,dic):
        '''
        :param table: str  Collections in a database 
        :param dic: dict  Query criteria 
        :return:  Return DeleteResult Object 
        '''
        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)
    #  Output  {'n': 21, 'ok': 1.0}

The above is how to use python operation MongoDB database details, more about python operation MongoDB database information please pay attention to other related articles on this site!


Related articles: