Last active
March 15, 2022 13:15
-
-
Save jpautom/abee7ed7e6241bb8f574 to your computer and use it in GitHub Desktop.
Tutorial pymongo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pymongo | |
# Connect | |
# Through a MongoDB URI. The database should contain permissions for the user, if provided | |
client = pymongo.MongoClient('mongodb://user:password@host/database') | |
# Create database | |
db = client["database"] | |
# Create collection | |
coll = db["collection"] | |
# Reference database/collection | |
coll = client.database.collection | |
# Insert | |
import datetime | |
post1 = {"author": "Mike", "text": "My first blog post!", "date": datetime.datetime.utcnow()} | |
post2 = {"author": "Mike", "text": "My second blog post!", "date": datetime.datetime.utcnow()} | |
# one | |
inserted_id = coll.insert_one(post1).inserted_id | |
# many | |
inserted_ids = coll.insert_many([post1, post2]).inserted_ids | |
# Query | |
# one | |
post = coll.find_one({"author": "Mike"}) # returns the object | |
# many | |
cursor = coll.find({"author": "Mike"}) # returns Cursor | |
for post in cursor: | |
print post | |
# Delete | |
# one | |
deleted_count = coll.delete_one({"author": "Mike"}).deleted_count | |
# many | |
deleted_count = coll.delete_many({"author": "Mike"}).deleted_count | |
# Update | |
# one | |
modified_count = coll.update_one({"author": "Mike"}, {"title": ""}).modified_count | |
# many | |
modified_count = coll.update_many({"author": "Mike"}, {"title": ""}).modified_count | |
# Indexing | |
# create | |
coll.create_index([('user_id', pymongo.ASCENDING)], unique=True) # can be multiindex | |
# list | |
list(coll.index_information()) | |
# Data transformations through "Aggregations" | |
pipeline = [ | |
{'$match': {'author': 'Mike'}}, #like find() syntax | |
{'$project': { | |
'name': '$author' #rename field | |
'text': True #include field | |
'comments': {'$literal': []}, #create field | |
}, | |
{'$out': 'superposts'} #write to new collection | |
] | |
coll.aggregate(pipeline) | |
# Delete collection | |
coll.drop() | |
# Delete database | |
client.database.drop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment