Python MongoDB Tutorial: Getting Started with MongoDB in Python

Installations

python -m pip install pymongo
import pymongo

Creating a Database

client = pymongo.MongoClient(port=27017)
import pymongo

client = pymongo.MongoClient(port=27017)
localdb = client['testdatabase']

Creating a Collection

import pymongo

client = pymongo.MongoClient(port=27017)
localdb = client['testdatabase']
localcol = localdb['testcollection']

Inserting Data

import pymongo

client = pymongo.MongoClient(port=27017)
localdb = client['testdatabase']
localcol = localdb['testcollection']

junkdata = { "first": "one", "second": "two" }
insertedRecord = localcol.insert_one(junkdata)

Verifying that our Database Exists

import pymongo

client = pymongo.MongoClient(port=27017)
list = client.list_database_names()
if "testdatabase" in list:
print('DB Exists')
Output:
DB Exists

Verifying that our Collection Exists

import pymongo

client = pymongo.MongoClient(port=27017)
localdb = client['testdatabase']
list = localdb.list_collection_names()
if "testcollection" in list:
print('Collection Exists')
Output:
Collection Exists

Conclusion

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How To Become a DevOps Engineer In Six Months or Less, Part 6: Run

ARMssembly 0 [picoCTF]

Cribl: Solving Customer Data Challenges

Moving away from moving gradients

How to make a killer news app for the mobile first world

News App

How to Dynamically Scrape Multiple Amazon Products Pages Using BeautifulSoup?

How to make graphs in VBA in a few minutes

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jesse L

Jesse L

More from Medium

How to use Python frozenset type

3 Steps to Coding Pythonic

Hackerrank — Insert Node in linked list walkthrough #Python #Hackerrank

Array Slicing in Python