MongoDB

Overview

MongoDB is a widely-used NoSQL database that is renowned for its document-based storage model. Unlike traditional relational databases, MongoDB stores data in BSON format, which is a binary representation similar to JSON. This format allows for flexible and complex data structures, making MongoDB an excellent choice for applications that require scalability, data distribution, high insert rates, and complex schemas. MongoDB is designed to scale across many nodes in multiple clusters, efficiently handling potentially billions of documents.

Setting Up MongoDB

To start experimenting with MongoDB, you need access to a MongoDB server. There are several ways to set up a MongoDB server:

  1. MongoDB Atlas: You can create a free account and instance on MongoDB.com, which provides a cloud-based solution for hosting your MongoDB databases.

  2. Local Installation: You can run a local MongoDB server using Docker with the following command:

    docker run -p 27017:27017 mongo
    

    This command will pull the MongoDB image from Docker Hub and run it on your local machine, making it accessible on port 27017.

  3. Package Managers: MongoDB servers can also be installed using package managers on various operating systems, including Linux, Mac, and Windows.

Example: Storing and Retrieving a Document

Below is an example of how to store and retrieve a document in MongoDB using Python:

import datetime
a_document = {'name': 'Jane',
              'age': 34,
              'interests': ['Python', 'databases', 'statistics'],
              'date_added': datetime.datetime.now()
}
db = client.my_data     #A
collection = db.docs   #B
result = collection.find_one()  #C
db.list_collection_names()
[]
#A Selects a database (which hasn’t been created yet)
#B Selects a collection in the database (also not yet created)
#C Searches for first item; no exception even if neither collection nor database exists yet

In this example, a document is created with fields such as name, age, interests, and date_added. The document is then stored in a MongoDB collection. The code demonstrates how to select a database and a collection, even if they have not been created yet. The find_one() method is used to search for the first item in the collection, and it does not raise an exception if the collection or database does not exist. This flexibility is one of the features that make MongoDB a powerful tool for developers.