Home > Mobile >  How to delete a document in MongoDB
How to delete a document in MongoDB

Time:11-28

I am trying to create a delete method in order to delete a document that has the key:"name" and the value:"Rhonda". Whenever I execute my current code, I get an AttributeError saying:"'AnimalShelter' object has no attribute 'delete'". How do I get the method to return the deleted document's JSON contents? Here is my code:

testing_script.ipynb

from animal_shelter import AnimalShelter
# now need to create the object from the class
shelter = AnimalShelter("aacuser","Superman")
data = {"age_upon_outcome":"2 years","animal_type":"Dog","breed":"Dachshund","color":"Black and tan","name":"Rhonda","outcome_subtype":"Partner","outcome_type":"Adopt","sex_upon_outcome":"Female"}
new_values = {"$set": {"age_upon_outcome":"3 years"}}

# if shelter.create(data):
#    print("Animal added")
# else:
#     print("Failed to add animal")

# Calls the read function
# shelter.read(data)

# Calls the update function
# shelter.update(data, new_values)

# Calls the delete function
shelter.delete(data)

output

AttributeError                            Traceback (most recent call last)
<ipython-input-5-60b1d887dfb8> in <module>
 17 
 18 # Calls the delete function
---> 19 shelter.delete(data)
 20 

AttributeError: 'AnimalShelter' object has no attribute 'delete'

animal_shelter.py

from pymongo import MongoClient
from bson.objectid import ObjectId

class AnimalShelter(object):
""" CRUD operations for Animal collection in MongoDB """

def __init__(self,username,password):
    # Initializing the MongoClient. This helps to 
    # access the MongoDB databases and collections. 
    # init to connect to mongodb without authentication
    self.client = MongoClient('mongodb://localhost:55996')
    # init connect to mongodb with authentication
    # self.client = MongoClient('mongodb://%s:%s@localhost:55996/?authMechanism=DEFAULT&authSource=AAC'%(username, password))
    self.database = self.client['AAC']

# Complete this create method to implement the C in CRUD.
def create(self, data):
    if data is not None:
        self.database.animals.insert(data)  # data should be dictionary  
        return True # Tells whether the create function ran successfully
    else:
        raise Exception("Nothing to save ...")

# Create method to implement the R in CRUD.     
def read(self, data):
    return self.database.animals.find_one(data) #returns only one

# Update method to implement the U in CRUD.
def update(self, data, new_values):
    if self.database.animals.count(data):
        self.database.animals.update(data, new_values)
        return self.database.animals.find({"age_upon_outcome":"3 years"})
    else:
        raise Exception("Nothing to update ...") 
        
# Delete method to implement the D in CRUD
def delete(self, data)
    result = self.database.animals.find_one_and_delete(data)
    # print the _id key only if the result is not None
    if("_id" in result):
        print("find_one_and_delete ID:",result["_id"])
    else:
        print("Nothing to delete")

CodePudding user response:

Problem is that functions that you are defining are outside the class. You have to put indentation on functions in class AnimalShelter

Also as pointed out in comment you are missing : in delete

Updated animal_sheltor.py

from pymongo import MongoClient
from bson.objectid import ObjectId

class AnimalShelter(object):
""" CRUD operations for Animal collection in MongoDB """

    def __init__(self,username,password):
    # Initializing the MongoClient. This helps to 
    # access the MongoDB databases and collections. 
    # init to connect to mongodb without authentication
        self.client = MongoClient('mongodb://localhost:55996')
    # init connect to mongodb with authentication
    # self.client = MongoClient('mongodb://%s:%s@localhost:55996/?authMechanism=DEFAULT&authSource=AAC'%(username, password))
        self.database = self.client['AAC']

# Complete this create method to implement the C in CRUD.
    def create(self, data):
        if data is not None:
            self.database.animals.insert(data)  # data should be dictionary  
            return True # Tells whether the create function ran successfully
        else:
            raise Exception("Nothing to save ...")

# Create method to implement the R in CRUD.     
    def read(self, data):
        return self.database.animals.find_one(data) #returns only one

# Update method to implement the U in CRUD.
    def update(self, data, new_values):
        if self.database.animals.count(data):
            self.database.animals.update(data, new_values)
            return self.database.animals.find({"age_upon_outcome":"3 years"})
        else:
            raise Exception("Nothing to update ...") 
        
# Delete method to implement the D in CRUD
    def delete(self, data):
        result = self.database.animals.find_one_and_delete(data)
    # print the _id key only if the result is not None
        if("_id" in result):
            print("find_one_and_delete ID:",result["_id"])
        else:
            print("Nothing to delete")

  • Related