MongoDB python 删除数据并删除集合

2021年3月11日17:06:40 发表评论 875 次浏览

先决条件:MongoDB基础, 插入和更新

目标 :

删除数据库中集合的条目/文档。假设集合名称为" my_collection"。

使用方法:

delete_one()或delete_many()

删除所有符合条件的文档:

以下操作将删除所有符合指定条件的文档。

result = my_collection.delete_many({"name": "Mr.Geek"})

要查看已删除的文档数:

print(result.deleted_count)

删除所有文件:

方法1:

使用delete_many()删除所有文档

result= my_collection.delete_many({})

方法2:使用collection.remove()删除所有文档

result = my_collection.remove()

删除的最佳方法是删除集合, 以便同时删除数据索引, 然后在该插入数据中创建一个新集合。

删除收藏集:

db.my_collection.drop()

我们首先在集合中插入一个文档, 然后根据查询将其删除。

# Python program to illustrate 
# delete, drop and remove
from pymongo import MongoClient
  
try :
     conn = MongoClient()
     print ( "Connected successfully!!!" )
except :  
     print ( "Could not connect to MongoDB" )
  
# database
db = conn.database
  
# Created or Switched to collection names: my_gfg_collection
collection = db.my_gfg_collection
  
emp_rec1 = {
         "name" : "Mr.Geek" , "eid" : 24 , "location" : "delhi"
         }
emp_rec2 = {
         "name" : "Mr.Shaurya" , "eid" : 14 , "location" : "delhi"
         }
emp_rec3 = {
         "name" : "Mr.Coder" , "eid" : 14 , "location" : "gurugram"
         } 
  
# Insert Data
rec_id1 = collection.insert_one(emp_rec1)
rec_id2 = collection.insert_one(emp_rec2)
rec_id3 = collection.insert_one(emp_rec3)
print ( "Data inserted with record ids" , rec_id1, " " , rec_id2, rec_id3)
  
# Printing the document before deletion
cursor = collection.find()
for record in cursor:
     print (record)
  
# Delete Document with name : Mr Coder
result = collection.delete_one({ "name" : "Mr.Coder" })
  
# If query would have been delete all entries with eid:14
# use this
# result = collection.delete_many("eid":14})
   
cursor = collection.find()
for record in cursor:
print (record)
OUTPUT (comment line denoted by #)

Connected successfully!!!
Data inserted with record ids     
#Data INSERT
{'_id': ObjectId('5a02227c37b8552becf5ed2b'), 'name': 
'Mr.GfG', 'eid': 45, 'location': 'noida'}
{'_id': ObjectId('5a0c734937b8551c1cd03349'), 'name': 
'Mr.Shaurya', 'eid': 14, 'location': 'delhi'}
{'_id': ObjectId('5a0c734937b8551c1cd0334a'), 'name': 
'Mr.Coder', 'eid': 14, 'location': 'gurugram'}
#Mr.Coder is deleted
{'_id': ObjectId('5a02227c37b8552becf5ed2b'), 'name': 
'Mr.GfG', 'eid': 45, 'location': 'noida'}
{'_id': ObjectId('5a0c734937b8551c1cd03349'), 'name': 
'Mr.Shaurya', 'eid': 14, 'location': 'delhi'}

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: