How to Get started with MongoDB?

Prakash R
featurepreneur
Published in
2 min readAug 26, 2021

MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. MongoDB offers high speed, high availability, and high scalability.

Python has a native library for MongoDB. The name of the available library is PyMongo. To import this, execute the following command:

from pymongo import MongoClient

Create a connection : The very first after importing the module is to create a MongoClient

from pymongo import MongoClient
client = MongoClient()

After this, connect to the default host and port. Connection to the host and port is done explicitly. The following command is used to connect the MongoClient on the localhost which runs on port number 27017.

client = MongoClient(“mongodb://localhost:27017/”)

Access DataBase Objects : To create a database or switch to an existing database we use:
Method 1 : Dictionary-style

mydatabase = client[‘name_of_the_database’]

Method 2:

mydatabase = client.name_of_the_database

Accessing the Collection : Collections are equivalent to Tables in RDBMS. We access a collection in PyMongo in the same way as we access the Tables in the RDBMS. To access the table, say table name “myTable” of the database, say “mydatabase”.

Method 1:

mycollection = mydatabase[‘myTable’]

Method 2:

mycollection = mydatabase.myTable

This record is stored as shown below in Database:

record = {
title: 'MongoDB and Python',
description: 'MongoDB is no SQL database',
tags: ['mongodb', 'database', 'NoSQL'],
viewers: 104
}

Insert the data inside a collection :

insert_one() or insert_many()rec = myTable.insert_one(record)

whole code looks like this shown below:

# importing module
from pymongo import MongoClient
# creation of MongoClient
client=MongoClient()
# Connect with the portnumber and host
client = MongoClient(“mongodb://localhost:27017/”)
# Access database
mydatabase = client[‘name_of_the_database’]
# Access collection of the database
mycollection=mydatabase[‘myTable’]
# dictionary to be added in the database
rec={
title: 'MongoDB and Python',
description: 'MongoDB is no SQL database',
tags: ['mongodb', 'database', 'NoSQL'],
viewers: 104
}
# inserting the data in the database
rec = mydatabase.myTable.insert(record)

--

--