mongodb_007.py

#! /usr/bin/python3
# ==================================================================
# drop document from collection
# ==================================================================

from pymongo import MongoClient
import pprint

pp = pprint.PrettyPrinter()

# ---- support function: display documents in collection

def display_documents(col,title):
    if not title == None:
        print(title)
    for x in col.find({},{"_id":0,"firstname": 1,"lasrname":1}):
        pp.pprint(x)

# ---- add documents to collection

database   = 'phonedb'
collection = 'phones'

docs = [ { 'firstname': 'Tom', 'lastname': 'Rot',
           'phonenumber': '666-555-8888' },
         { 'firstname': 'Tom', 'lastname': 'Terrific',
           'nickname': 'cool breeze' },
         { 'firstname': 'Judy', 'lastname': 'O',
           'phonenumber': '(555) 123-4567' } ]

client = MongoClient()
db     = client[database]
col    = db[collection]

x = col.insert_many(docs)

display_documents(col,'before delete ------------------')

query = { 'firstname' : 'Tom' }

x = col.delete_many(query)

print(f'{x.deleted_count} documents deleted')  

display_documents(col,'after delete -------------------')

# ---- delete all documents in the collection

x = col.delete_many({})

print(f'{x.deleted_count} documents deleted') 

display_documents(col,'after delete all----------------')