Friday, December 1, 2023

MyLearning - MongoDB with Python

What's the goal of this learning?

Quickly get hands dirty with the concepts of MongoDB by using Python

Setup

What is MongoDB Atlas?

It is a cloud service provided by MongoDB, and I will utilize this cloud instance instead of a local one. I signed up for it at the following URL using my Google account to avail free subscription.

Create a cluster

  • To create cluster through UI follow this doc and you'll get the username and password
  • [Optional] To create cluster using CLI
    • First, install Atlas CLI
      • brew install mongodb-atlas
    • Connect the Atlas CLI to account
      • atlas auth login
    • atlas clusters create [name]
      • atlas clusters create siddesh 

PyMongo - The Python MongoDB Driver library

  • pip install pymongo

Compass - GUI application

  • Refer this page for installation 

Python Code

# create a connection to MongoDB
CONNECTION_STRING = "mongodb+srv://%s:%s@cluster0.rosqiu8.mongodb.net/retryWrites=true&w=majority" % (  username, password)
client = MongoClient(CONNECTION_STRING)

# Create database
db_name = client["user_shopping_list"]

# Create collection
collection = db_name["samskruthi_items"]

# Insert items
item_1 = {
        "item_name": "Phone Holder",
        "max_discount": "10%",
        "batch_number": "RR450020FRG",
        "price": 500,
        "category": "Accessory"
    }

    item_2 = {
        "item_name": "Cake",
        "category": "food",
        "quantity": 1,
        "price": 1200,
        "item_description": "Unicorn theme chocolate flavor cake"
    }

collection.insert_many([item_1, item_2])

# Query collection
item_details = collection.find()
for item in item_details:
    print(item)

# Create an index on the collection
Indexes make database search faster and more efficient, and reduce the cost of querying on operations such as sort, count, and match

index = collection.create_index(field_name)

# Query by field name
item_details = collection.find({"category": "food"})




MongoDB Concepts

How MongoDB stores data?

MongoDB stores data in JSON like documents.

Example:

# Mongodb document (JSON-style)
document_1 = {
  "item_name": "Cake",
  "category": "food",
  "quantity": 1,
  "price": 1200,
  "item_description": "Unicorn theme chocolate flavor cake"
}

DB 

A database is a container for collections

Collections

A collection is a group of MongoDB documents. It's similar to a table in relational databases

Document

A document is a basic unit of data in MongoDB, similar to a row in a relational database. Documents are BSON objects (binary-encoded JSON)

Field

A field is a key-value pair in a MongoDB document

References

  1. https://www.mongodb.com/languages/python 

No comments: