Analysis on the operation method between Python and Mongodb database

  • 2021-07-06 11:10:22
  • OfStack

Directory 1. Install Mongodb and pymongo 1.1 Create a directory where Mongodb data files are stored: 1.2 Execute commands respectively: 1.3 Install pymongo2. Connect to database, specify database, specify collection, insert data: 3. Query, count, sort, offset: 4. Update: 4.1 Update data without $set: 4.2 Update data with $set: 4.3 Difference 4.4 Difference between update_one and update_many: 5 Delete: 6 Other

MongoDB is one of the most popular NoSQL databases, using the data type BSON (similar to JSON).

1. Install Mongodb and pymongo

Installation and Configuration of Mongodb

Please search for the installation tutorial of Mongodb online. After the installation is completed, perform the following configuration process:

1.1 Create a directory where Mongodb data files are stored:

* Note: I am not using an root user, so I changed the owner of the directory. *


sudo mkdir /data
sudo chown -R python:python /data
mkdir /data/db

1.2 Execute the commands separately:

The first command is to specify the port and save path, and the second command is to run the mongodb database.


mongod --port 27017 --dbpath /data/db
mongo --port 27017

1.3 Installing pymongo

sudo pip3 install pymongo

2. Connect to database, specify database, specify collection, insert data:

mongodb stores data as key values, so fields are used to insert data in Python.


import pymongo
# Connect mongodb
client = pymongo.MongoClient('mongodb://localhost:27017/')
# Specify the database 
db = client.test4
# Specify the collection 
collection = db.students
# Data 
student1 = {
 'id': '201801',
 'name': 'Jack',
 'age': 20,
 'gender': 'male'
}
student2 = {
 'id': '201802',
 'name': 'Tom',
 'age': 22,
 'gender': 'male'
}
student3 = {
 'id': '201803',
 'name': 'Rose',
 'age': 21,
 'gender': 'female'
}
student4 = {
 'id': '201804',
 'name': 'Mike',
 'age': 20,
 'gender': 'female'
}
student5 = {
 'id': '201805',
 'name': 'Ray',
 'age': 20,
 'gender': 'female'
}
student6 = {
 'id': '201806',
 'name': 'Alan',
 'age': 21,
 'gender': 'male'
}
# Insert 1 Bar data 
result1 = collection.insert_one(student1)
print(result1)
print(result1.inserted_id)
# # Insert multiple pieces of data 
result2 = collection.insert_many([student2, student3, student4, student5, student6])
print(result2)
print(result2.inserted_ids)

Run results:

insert method:

5b3a1942971951218d41c02b
[ObjectId('5b3a1942971951218d41c02c'), ObjectId('5b3a1942971951218d41c02d')]

Official recommendation:


<pymongo.results.InsertOneResult object at 0x7fa4cc363ec8>
5b3a1942971951218d41c02e
<pymongo.results.InsertManyResult object at 0x7fa4cc363f08>
[ObjectId('5b3a1942971951218d41c02f'), ObjectId('5b3a1942971951218d41c030')]

3. Query, count, sort, offset:


import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
# Query 1 Bar data 
print(' Single data ','='*50)
result = collection.find_one({'name': 'Jack'})
print(result)
print(' Multiple pieces of data ','='*50)
# Query multiple pieces of data 
for res in collection.find({'age': {'$mod': [5, 0]}}):
 print(res)
# Count 
print(' Count ','='*50)
count = collection.find({'age': {'$mod': [5, 0]}}).count()
print(count)
# Sort 
print(' Sort ','='*50)
results = collection.find().sort('name', pymongo.ASCENDING) # Ascending order , pymongo.DESCENDING In descending order 
print([result['name'] for result in results])
# Migration 
print(' Migration ','='*50)
results = collection.find().sort('name', pymongo.ASCENDING).skip(2) # Migration 2 Bit , Ignore the first two data 
print([result['name'] for result in results])
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2) # Output only 2 Data 
print([result['name'] for result in results])
find({ ' age': {'$mod': [5, 0]}}):  Indicates the search age to retrieve the remainder 5 Surplus 0 Value of .  There are also many comparison symbols ,  Please Baidu .

Run results:


 Single data  ==================================================
{'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 20, 'gender': 'male'}
 Multiple pieces of data  ==================================================
{'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 20, 'gender': 'male'}
{'_id': ObjectId('5b3a1942971951218d41c02e'), 'id': '201804', 'name': 'Mike', 'age': 20, 'gender': 'female'}
{'_id': ObjectId('5b3a1942971951218d41c02f'), 'id': '201805', 'name': 'Ray', 'age': 20, 'gender': 'female'}
 Count  ==================================================
3
 Sort  ==================================================
['Alan', 'Jack', 'Mike', 'Ray', 'Rose', 'Tom']
 Migration  ==================================================
['Mike', 'Ray', 'Rose', 'Tom']
['Mike', 'Ray']

4. Update:

4.1 Update data without $set:


import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
# Modify 
condition = {'name': 'Jack'}
student = collection.find_one(condition) # Get satisfaction condition Data of 
print(' Before updating : ', student)
student['age'] = 22 # Modify age 
result = collection.update(condition, student) # Will change the modified student Replace condition
print(' After updating ', collection.find_one(condition))
# Updated return value 
print(result) #ok=1 Represents successful execution , nModified Number of items representing influence 

Run results:


 Before updating : {'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 20, 'gender': 'male'}
 After updating  {'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 22, 'gender': 'male'}
{'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}

4.2 Update data with $set:


import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
# Use $set Update 
condition = {'name': 'Jack'}
student = collection.find_one(condition) # Get satisfaction condition Data of 
print(' Before updating : ', student)
student['age'] = 23 # Modify age 
result = collection.update(condition, {'$set': student}) # Will change the modified student Replace condition, $set Focus on 
print(' After updating ', collection.find_one(condition))
# Updated return value 
print(result) #ok=1 Represents successful execution , nModified Number of items representing influence 

Run results:


 Before updating : {'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 22, 'gender': 'male'}
 After updating  {'_id': ObjectId('5b3a1942971951218d41c02b'), 'id': '201801', 'name': 'Jack', 'age': 23, 'gender': 'male'}
{'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}

Comparing the data with and without $set updates, there is no difference at this point.

Here are the differences:

4.3 Differences


mongod --port 27017 --dbpath /data/db
mongo --port 27017
0

Run results:

Use:


mongod --port 27017 --dbpath /data/db
mongo --port 27017
1

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =


mongod --port 27017 --dbpath /data/db
mongo --port 27017
2

Analyze the above running results, You can find that when you use $set, If the updated data has fields that the original data does not have, This field is added to the original data (mother is added in the above example) without deleting any fields. On the contrary, if set is not used, the fields that are not in the updated data will be deleted from the original data, and the new fields will be added (mother is deleted and father is added in the above example. It can also be understood as completely replacing the original data with the updated data.)

4.4 Differences between update_one and update_many:


import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
# Official Recommended Use 
#update_one And update_many Difference between 
print('update_one: ')
condition = {'age': {'$gt': 20}}
result = collection.update_one(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)
# Partition line 
print()
print('='*20, ' Partition line ', '='*20)
print()
print('update_many: ')
condition = {'age': {'$gt': 20}}
result = collection.update_many(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)

Run results:


mongod --port 27017 --dbpath /data/db
mongo --port 27017
4

5. Delete:


mongod --port 27017 --dbpath /data/db
mongo --port 27017
5

Run results:

{'ok': 1, 'n': 1}
1
2

6. Others

In addition to the above commonly used ones, it also includes find_one_and_delete () to be deleted after searching, and find_one_and_replace () to be replaced after searching. If you are interested, you can learn more about it by Baidu.

Summarize


Related articles: