Develop a Python module in a PY file, using object-oriented programming methodology, to enable create and read
Fantastic news! We've Found the answer you've been seeking!
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, 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:
- A method that inserts a document into a specified MongoDB database and collection
- Input -> argument to function will be set of key/value pairs in the data type acceptable to the MongoDB driver insert API call
- Return -> “True” if successful insert, else “False”
- A method that queries for documents from a specified MongoDB database and specified collection
- Input -> arguments to function should be the key/value lookup pair to use with the MongoDB driver find API call
- 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.
Related Book For
Database Systems Design Implementation and Management
ISBN: 978-1285196145
11th edition
Authors: Carlos Coronel, Steven Morris
Posted Date: