Question: Develop a Python module in a PY file, using object-oriented programming methodology, to enable create and read functionality for the database. To support code reusability,

Develop a Python module in a PY file, using object-oriented programming methodology, to enable create and read functionality for the database. To support code reusability, your Python code needs to be importable as a module by other Python scripts.

Develop a CRUD class that, when instantiated, provides the following functionality:

  1. A method that inserts a document into a specified MongoDB database and collection
    1. Input -> argument to function will be set of key/value pairs in the data type acceptable to the MongoDB driver insert API call
    2. Return -> “True” if successful insert, else “False”
  2. A method that queries for documents from a specified MongoDB database and specified collection
    1. Input -> arguments to function should be the key/value lookup pair to use with the MongoDB driver find API call
    2. Return -> result in cursor if successful, else MongoDB returned error message

Can someone help clarify how to create a class that inserts and queries documents in mongoDB?

Example Python Code to Insert a Document from pymongo import MongoClient from bson.objectid import ObjectIdclass 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.         self.client = MongoClient('mongodb://%s:%s@localhost:27017' % (username, password))        self.database = self.client['project']# 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                    else:            raise Exception("Nothing to save, because data parameter is empty")# Create method to implement the R in CRUD.

Step by Step Solution

3.54 Rating (168 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

it is the example python module that uses objectoriented programming methodology to provide create and read functionality for a MongoDB database impor... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!