GithubHelp home page GithubHelp logo

ansmirnov / python-pymongo-usage Goto Github PK

View Code? Open in Web Editor NEW
0.0 2.0 0.0 34 KB

Examples of CRUD in MongoDB using the pymongo Python module

Dockerfile 100.00%
mongodb mongodb-database mongodb-python mongodb-client databases document-database nosql crud mongodb-crud

python-pymongo-usage's Introduction

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/

python-pymongo-usage's People

Contributors

ansmirnov avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.