Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

ansmirnov/python-pymongo-usage

Open more actions menu

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

80 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Python PyMongo usage

Contents

System environment

  • Deployed MongoDB 4.4.3
  • Python 3.9.1

Install pymongo

pip install pymongo==3.11.3

Imports

import os
from pprint import pprint
from pymongo import MongoClient

Initialize the connection

Parameters

MONGODB_USERNAME = os.environ.get("MONGODB_USERNAME")
MONGODB_PASSWORD = os.environ.get("MONGODB_PASSWORD")
MONGODB_HOST = os.environ.get("MONGODB_HOST")
MONGODB_DATABASE = os.environ.get("MONGODB_DATABASE")
MONGODB_COLLECTION = os.environ.get("MONGODB_COLLECTION")

Construct the URI

uri = f"mongodb://{MONGODB_USERNAME}:{MONGODB_PASSWORD}@{MONGODB_HOST}"

Connect to the MongoDB

connection = MongoClient(uri)

Select the database

db = connection[MONGODB_DATABASE]

Select the collection

collection = db[MONGODB_COLLECTION]

Prepare the arguments

Example docs

One doc

doc = {
    "item": "canvas",
    "qty": 100,
    "tags": ["cotton"],
    "size": {
	"h": 28,
	"w": 35.5,
	"uom": "cm"
    }
}

Many doc

docs = [
    {
        "item": "journal",
        "qty": 25,
        "size": {"h": 14, "w": 21, "uom": "cm"},
        "status": "A"
    },
    {
        "item": "notebook",
        "qty": 50,
        "size": {"h": 8.5, "w": 11, "uom": "in"},
        "status": "A"
    },
    {
        "item": "paper",
        "qty": 100,
        "size": {"h": 8.5, "w": 11, "uom": "in"},
        "status": "D"
    },
    {
        "item": "planner",
        "qty": 75,
        "size": {"h": 22.85, "w": 30, "uom": "cm"},
        "status": "D"
    },
    {
        "item": "postcard",
        "qty": 45,
        "size": {"h": 10, "w": 15.25, "uom": "cm"},
        "status": "A"
    }
]

Queries

Select All Documents in a Collection

query = {}

Specify Equality Condition

query = {"status": "D"}

Specify Conditions Using Query Operators

query = {"status": {"$in": ["A", "D"]}}

Specify AND Conditions

query = {"status": "A", "qty": {"$lt": 30}}

Specify OR Conditions

query = {"$or": [{"status": "A"}, {"qty": {"$lt": 30}}]}

Specify AND as well as OR Conditions

query = {
    "status": "A",
    "$or": [{"qty": {"$lt": 30}}, {"item": {"$regex": "^p"}}]
}

Update Operators

Set the value of a field to current date

update_operator = {
    "$currentDate": {
        "current_date_default": True,
        "current_date": {"$type": "date"},
        "current_timestamp": {"$type": "timestamp"}
    }
}

Increment the value of the field by the specified amount

update_operator = {
    "$inc": {
        "emptyField": 1,
        "a.a": 1,
    }
}

Aggregation Operators

pipeline = []

Limit

pipeline.append({
    "$limit": 100,
})

Match

pipeline.append({
    "$match": {"status": "A"}
})

Projection

pipeline.append({
    "$project": {"status": 1}
})

Sort

pipeline.append({
    "$sort": {"status": -1}
})

Run the command

Insert Documents

Insert one document

collection.insert_one(doc)

Insert multiple documents

collection.insert_many(docs)

Number of documents in the collection

collection.count_documents(query)

Find documents

cursor = collection.find(query)

Update Documents

Update one

collection.update_one(query, update_operator)

Update many

collection.update_many(query, update_operator)

Replace documents

collection.replace_one(query, doc)

Delete Documents

Delete one

collection.delete_one(query)

Delete many

collection.delete_many(query)

Aggregate operator

cursor = collection.aggregate(pipeline, allowDiskUse=True)

Print the cursor data

for doc in cursor:
     pprint(doc)

Docker container

Dockerfile

FROM python:3.9.1-buster
RUN pip install pymongo==3.11.3

Build the image

docker build -t python-pymongo-usage .

Configure

MONGODB_USERNAME=user
MONGODB_PASSWORD=topsecret
MONGODB_HOST=mongodb
MONGODB_DATABASE=newdb
MONGODB_COLLECTION=testcollection

Run the container

docker run --rm --link mongodb --env-file .env -it python-pymongo-usage python

References

  1. https://docs.mongodb.com/manual/crud/
Morty Proxy This is a proxified and sanitized view of the page, visit original site.