MondoDB's use of MongoDB python delete data MondoDB -10

We can use  delete_one () method to delete a document, which is the first parameter query object, specify which data to delete.

As used herein, the test data as follows (click image to enlarge):

Examples of what to delete name field is "Taobao" document:

import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["runoobdb"]
mycol = mydb["sites"]
 
myquery = { "name": "Taobao" }
 
mycol.delete_one(myquery)
 
# 删除后输出
for x in mycol.find():
  print(x)

The output is:

Delete multiple documents

We can use  delete_many () method to delete multiple documents, which is the first parameter query object, specify which data to delete.

Delete all name field begins with F document:

import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["runoobdb"]
mycol = mydb["sites"]
 
myquery = { "name": {"$regex": "^F"} }
 
x = mycol.delete_many(myquery)
 
print(x.deleted_count, "个文档已删除")

The output is:

A document has been deleted

Delete all documents in the collection

delete_many () method if passed an empty query object, all documents in the collection will be deleted:

import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["runoobdb"]
mycol = mydb["sites"]
 
mycol.drop()

If you delete a successful drop () returns true, if the delete fails (collection does not exist) returns false.

We use the following command to check whether the collection has been deleted in the terminal:

> use runoobdb
switched to db runoobdb
> show tables;

 

Guess you like

Origin www.cnblogs.com/hela/p/11289123.html