Back to all posts

MongoDB connect with Python

Python needs a MongoDB driver to access the MongoDB database. We will use the MongoDB driver "PyMongo". # Creating a Database import pymongo myclient = pym…

Python needs a MongoDB driver to access the MongoDB database. We will use the MongoDB driver "PyMongo".

Python
# Creating a Database

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")

# Creating a Database
mydb = myclient["mydatabase"] # In MongoDB, a database is not created until it gets content!

# Creating a Collection
mycol = mydb["customers"] #  In MongoDB, a collection is not created until it gets content!

# Insert Into Collection
mydict = { "name": "John", "address": "Highway 37" }
x = mycol.insert_one(mydict)

mylist = [
  { "name": "Amy", "address": "Apple st 652"},
  { "name": "Hannah", "address": "Mountain 21"},
  { "name": "Michael", "address": "Valley 345"},
  { "name": "Sandy", "address": "Ocean blvd 2"},
  { "name": "Betty", "address": "Green Grass 1"},
  { "name": "Richard", "address": "Sky st 331"},
  { "name": "Susan", "address": "One way 98"},
  { "name": "Vicky", "address": "Yellow Garden 2"},
  { "name": "Ben", "address": "Park Lane 38"},
  { "name": "William", "address": "Central st 954"},
  { "name": "Chuck", "address": "Main Road 989"},
  { "name": "Viola", "address": "Sideway 1633"}
]

x = mycol.insert_many(mylist)
Bash
myresult = mycol.find()
for x in myresult:
  print(x)

Keep building your data skillset

Explore more SQL, Python, analytics, and engineering tutorials.