MongoDB with Python & Atlas MongoDB

mongodb logo at mongodb with python page

This page gives examples for advanced Python users on how to use MongoDB with Python. You can refer to the video below for more detailed explanations.

				
					import pprint
from pymongo import MongoClient
import datetime


password = 'XxXXxxxxXXXxxx'
connection_string = f'mongodb+srv://yourusername:{password}@cluster0.abcdef.mongodb.net/test'

client = MongoClient(connection_string)

# reading ----------------------------------------------------

# making print output nicer
printer = pprint.PrettyPrinter()


# get all databases
def get_databases(value='full'):
    if value == 'names':
        dbs_names = client.list_database_names()
        return dbs_names

    else:
        dbs = client.list_databases()
        return [i for i in dbs]


def get_database_collections(db_name):
    collections = db_name.list_collection_names()
    return collections


def get_document_in_a_collection(db_name, collection_name):
    collection = db_name[collection_name]
    cursor = collection.find({})
    for i in cursor:
        printer.pprint(i)


def get_document_by_id(db_name, collection_name, doc_id):
    # from bson.objectid import ObjectId
    #
    # _id = ObjectId(doc_id)
    document = db_name[collection_name].find_one({"_id": doc_id})
    printer.pprint(document)


def get_document_by_object_id(db_name, collection_name, doc_id):
    from bson.objectid import ObjectId
    _id = ObjectId(doc_id)
    document = db_name[collection_name].find_one({"_id": _id})
    printer.pprint(document)


def get_project_columns(db_name, collection_name, columns):
    document = db_name[collection_name].find({}, columns)
    for i in document:
        print(i)
        

def get_age_range(db_name, collection_name, min_date, max_date):
    query = {"$and": [
        {"birthdate": {"$gte": min_date}},
        {"birthdate": {"$lte": max_date}}
    ]}

    document = db_name[collection_name].find(query).sort("birthdate")
    for i in document:
        printer.pprint(i)



# # # TEST

# # print just names as list
# print(get_databases('names'))
#
# # print collections inside top10board database
# print(get_database_collections(client.top10board))
#
# # print values in a collection
# get_document_in_a_collection(client.top10board, 'items')
#
# # print document by id (which is manually generated)
# get_document_by_id(client.top10board, 'items', 1)

# # print document by id (with ObjectId property)
# get_document_by_object_id(client.sample_analytics, 'customers', '5ca4bbcea2dd94ee58162a68')

# # printing values only by username, name as specified. 1 means show.
# # id=0 means don't print the objectId / ID otherwise it will be shown by default.
# get_project_columns(client.sample_analytics, 'customers', {"_id": 0, "username": 1, "name": 1})

# find between years 1990 ~ 1991 dates
get_age_range(client.sample_analytics, 'customers', datetime.datetime(1990, 1, 1, 0, 0, 0), datetime.datetime(1991, 1, 1, 0, 0, 0))

				
			

These are the most commonly used MongoDB operators:

  1. Comparison Operators:
  • $eq: Matches values that are equal to a specified value
  • $ne: Matches all values that are not equal to a specified value
  • $gt: Matches values that are greater than a specified value
  • $gte: Matches values that are greater than or equal to a specified value
  • $lt: Matches values that are less than a specified value
  • $lte: Matches values that are less than or equal to a specified value
  • $in: Matches any of the values specified in an array
  • $nin: Matches none of the values specified in an array

 

  1. Logical Operators:
  • $and: Joins query clauses with a logical AND
  • $or: Joins query clauses with a logical OR
  • $not: Inverts the effect of a query expression
  • $nor: Joins query clauses with a logical NOR

 

  1. Element Operators:
  • $exists: Matches documents that have the specified field
  • $type: Selects documents if a field is of the specified type

 

  1. Array Operators:
  • $all: Matches arrays that contain all elements specified in the query
  • $elemMatch: Selects documents if the array field contains at least one element that matches all the specified criteria
  • $size: Matches arrays that contain a specific number of elements

 

  1. Evaluation Operators:
  • $expr: Allows use of aggregation expressions within the query language
  • $jsonSchema: Validate documents against the given JSON Schema
  • $mod: Performs a modulo operation on the value of a field and selects documents with a specified result
  • $regex: Selects documents where values match a specified regular expression
  • $text: Performs text search
  • $where: Matches documents that satisfy a JavaScript expression

Here is helpful video on YouTube that covers main subjects:

Social Share: