MongoDB 101

Get started with MongoDB using pymongo: Learn CRUD operations and build a BookStore app with Flask

Today when I am searching Dev jobs, I found that my database knowledge is weak.

And one job requirements mentioned MERN stack, what is that?

The MERN stack is a collection of open-source technologies that use JavaScript to build web applications. MERN is an acronym for the four technologies that make up the stack:

  • MongoDB: A cross-platform, document-oriented, NoSQL database

  • Express: A Node.js framework that simplifies back-end code writing

  • React: A front-end library

  • Node.js: A back-end framework

So let's crack some database knowledge typically in MongoDB today 😈.

I am using Python often, so here's a brief tutorial on how to use MongoDB with Python using the pymongo library.

  1. Installation First, you need to install MongoDB on your system. You can download it from the official MongoDB website. After that, you need to install pymongo, which is a Python driver for MongoDB.

     pip install pymongo
    
  2. Connection To connect to MongoDB, you need to create a MongoClient object and specify the host and port number.

    💡
    MongoDB is a server-based database system. It runs as a separate process on a machine and listens for connections from client applications. By default, MongoDB listens for connections on port 27017, and localhost is the hostname that refers to the current device used to access it. You can configure MongoDB to listen on a different port if needed.
     from pymongo import MongoClient
     client = MongoClient('localhost', 27017)
    
  3. Database You can access a database by specifying its name as an index to the MongoClient instance.

     db = client['mydatabase']
    
  4. Collection Collections are equivalent to tables in relational databases. You can access a collection in a similar way to accessing a database.

     collection = db['mycollection']
    
  5. Insert You can insert a document into a collection using the insert_one() or insert_many() method.

     document = {"name": "John", "age": 30, "city": "New York"}
     collection.insert_one(document)
    
  6. Find You can find documents using the find_one() or find() method.

     document = collection.find_one({"name": "John"})
    
  7. Update You can update a document using the update_one() or update_many() method.

     collection.update_one({"name": "John"}, {"$set": {"city": "London"}})
    
  8. Delete You can delete a document using the delete_one() or delete_many() method.

     collection.delete_one({"name": "John"})
    

This is a very basic introduction to MongoDB with Python. There are many more features and options available in pymongo that you can use to interact with MongoDB.

I think it is super easy, when you using it, there is a cheat sheet which is awesome👏.

And, in real world, we need implementations, right? Let's create a simple application for managing a book store. We'll create a BookStore class with methods for CRUD(creating, reading, updating, and deleting) books.

from pymongo import MongoClient

class BookStore:
    def __init__(self, db_name='bookstore', collection_name='books'):
        self.client = MongoClient('localhost', 27017)
        self.db = self.client[db_name]
        self.collection = self.db[collection_name]

    def add_book(self, title, author, published_year):
        book = {
            "title": title,
            "author": author,
            "published_year": published_year
        }
        return self.collection.insert_one(book)

    def get_book(self, title):
        return self.collection.find_one({"title": title})

    def get_all_books(self):
        return list(self.collection.find())

    def update_book(self, title, field, value):
        return self.collection.update_one({"title": title}, {"$set": {field: value}})

    def delete_book(self, title):
        return self.collection.delete_one({"title": title})

Then, let's consider a Flask web application, you might create a single BookStore instance when your application starts, and store it in the application's context for efficiency. Here's how you might do it:

from flask import Flask, g, jsonify
from bookstore import BookStore

app = Flask(__name__)

def get_bookstore():
    if 'bookstore' not in g:
        g.bookstore = BookStore()
    return g.bookstore

@app.teardown_appcontext
def close_bookstore(e=None):
    bookstore = g.pop('bookstore', None)
    if bookstore is not None:
        bookstore.close()

@app.route('/books', methods=['GET'])
def get_books():
    bookstore = get_bookstore()
    books = bookstore.get_all_books()
    return jsonify(books)

if __name__ == "__main__":
    app.run(debug=True)

In this example, the get_books function retrieves all books from the bookstore, converts them to JSON using jsonify, and returns them as a response. The jsonify function takes care of setting the appropriate content type (application/json), converting the Python dictionary to a JSON string, and creating a response object.

The @app.teardown_appcontext decorator registers a function that's called when the application context is torn down. This is where you can close the database connection.

This way, you're reusing the same BookStore instance (and hence the same database connection) across multiple requests, which is much more efficient than creating a new BookStore instance for each request.

Voilà! Here the brief summary of this article using HashNode AI🤖

This article explores the MERN stack and provides a tutorial on using MongoDB with Python through the pymongo library. It covers basic database operations such as connecting to MongoDB, inserting, finding, updating, and deleting documents. Additionally, it demonstrates how to create a simple BookStore application using pymongo and integrates it with a Flask web application to manage books efficiently.