This is the 27th day of my participation in Gwen Challenge
If ❤️ my article is helpful, welcome to comment, follow, like. This is the biggest encouragement for me to continue my technical creation. More previous posts on my personal blog
Delete the data
For example, we found that li Si – English score was inserted repeatedly when it was newly added, so we should delete one of them as follows:
ret2delete = collect.delete_one({"student_name" : "Bill"."subject" : "English"})
print(ret2delete)
# <pymongo.results.DeleteResult object at 0x000001D4AA0D15C8>
Copy the code
Delete them all?
ret2delete = collect.delete_many({"student_name" : "Bill"."subject" : "English"})
print(ret2delete)
Copy the code
Modify the data
For example, we found that the new test score data was added earlier, and there was a lack of test time. We need to update the data. We can do this:
# Update single
ret2update = collect.update_one({"class_name" : "Class 1, Senior 3"}, {"$set": {"date":"20200301"}})print(ret2update.matched_count) # 1
# update multiple
ret2update = collect.update_many({"class_name" : "Class 1, Senior 3"}, {"$set": {"date":"20200301"}})print(ret2update.matched_count) # 3
Copy the code
$set tells PyMongo that I’m only updating the date field in the document. If $set is missing, the entire document is replaced with {“date”:”20200301″}}
$inc = $set; $inc = $set;
ret2update = collect.update_one({"class_name" : "Class 1, Senior 3"}, {"$inc": {"score":"1"} })
ret2update = collect.update_one({"class_name" : "Class 1, Senior 3"}, {"$inc": {"score":"0.5"}})print(ret2update.matched_count) # 3
Copy the code
And from the official mongodb documentation, we can know$inc
Is atomic operation, suitable for concurrent applications
Other operating
After we have retrieved some of the data we want, we are left with the aggregation operation:
Statistics of the number
totalnum = collect.find().count()
Copy the code
The sorting
To sort, you simply call sort() and pass in the sorted fields and the ascending flags. The following is an example:
results = collect.find().sort('name', pymongo.ASCENDING)
print([result['name'] for result in results])
Copy the code
paging
The skip() offset method is called when paging, with limit() specifying the number of results
results = collect.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)
print([result['name'] for result in results])
Copy the code