Skip to content

Instantly share code, notes, and snippets.

@ibelgin
Last active October 17, 2020 09:42
Show Gist options
  • Save ibelgin/0ddf1275becbba3679f1218fc7cd9e02 to your computer and use it in GitHub Desktop.
Save ibelgin/0ddf1275becbba3679f1218fc7cd9e02 to your computer and use it in GitHub Desktop.
This is The Basic Usage Of MongoDB With Python
# Importing Python MongoDB Connector
# Can Be Installed By -> "pip install pymongo"
import pymongo
# For Working With Date And Time
import datetime
# This Is The Connector With The URL From MongoDB Atlas
client = pymongo.MongoClient('...') # Enter Your URL From MongoDB Atlas
# Creating Collection Object
db = client["User_Details"]
# Creating The DB Object
records = db["users"]
# -- Reading Data
# This Will Print All The Data As Dictionary
for i in list(records.find()):
print(i)
# This Will Search For The Data And Send The Dictionary Of It
# out[0]: {'_id': ObjectId('5f84030991186a218bf3b62d'), 'name': 'Belgin'}
print(records.find_one({'name':"Belgin"}))
# --- Inserting Data
# Sample Data To Insert
personDocument = {
"name":"Belgin Android",
"age":17,
"Instagram":"https://www.instagram.com/reactnative.modules/",
"birth": datetime.datetime(2003, 06, 11)
}
# Command To Insert A Single Data To The DataBase
# -> <database_onject>.insert_one(<Data>)
# If Insert Was Sucessful You will get a similar message
# out[1]: <pymongo.results.InsertOneResult object at 0x10950e5f0>
print(records.insert_one(personDocument))
# --- Updating Data
# This Will Update All The Value Of The Given Object To The Other Object
records.update_one({'name': "Belgin"}, {'$set': {'name':"Value Changed"}})
# Now Running The Read Function Will Give The Following Output
# out[2]: {'_id': ObjectId('5f84030991186a218bf3b62d'), 'name': 'Value Changed'}
# --- Deleting Data
# This Command Will Delete The Whole Dictionary
records.delete_one({'name':"Belgin Android"})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment