Prerequisite : MongoDB : An introduction
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.
The next question which arises in the mind of the people is “Why MongoDB”?
Reasons to opt for MongoDB :
- It supports hierarchical data structure (Please refer docs for details)
- It supports associate arrays like Dictionaries in Python.
- Built-in Python drivers to connect python-application with Database. Example- PyMongo
- It is designed for Big Data.
- Deployment of MongoDB is very easy.
MongoDB vs RDBMS

MongoDB and PyMongo Installation Guide
- First start MongoDB from command prompt using :
Method 1:
mongod
or
Method 2:
net start MongoDB

See port number by default is set 27017 (last line in above image).
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(‘host’, port_number)
example: - client = MongoClient(‘localhost’, 27017 )
|
It can also be done using the following command:
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’]
|
Method2 :
mydatabase = client.name_of_the_database
|
If there is no previously created database with this name, MongoDB will implicitly create one for the user.
Note : The name of the database fill won’t tolerate any dash (-) used in it. The names like my-Table will raise an error. So, underscore are permitted to use in the name.
- 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
|
>MongoDB store the database in the form of dictionaries as shown:>
record = {
title: 'MongoDB and Python',
description: 'MongoDB is no SQL database',
tags: ['mongodb', 'database', 'NoSQL'],
viewers: 104
}
‘_id’ is the special key which get automatically added if the programmer forgets to add explicitly. _id is the 12 bytes hexadecimal number which assures the uniqueness of every inserted document.
- Insert the data inside a collection :
Methods used:
insert_one() or insert_many()
We normally use insert_one() method document into our collections. Say, we wish to enter the data named as record into the ’myTable’ of ‘mydatabase’.
rec = myTable.insert_one(record)
|
The whole code looks likes this when needs to be implemented.
from pymongo import MongoClient
client = MongoClient()
client = MongoClient(“mongodb: / / localhost: 27017 / ”)
mydatabase = client[‘name_of_the_database’]
mycollection = mydatabase[‘myTable’]
rec = {
title: 'MongoDB and Python' ,
description: 'MongoDB is no SQL database' ,
tags: [ 'mongodb' , 'database' , 'NoSQL' ],
viewers: 104
}
rec = mydatabase.myTable.insert(record)
|
- Querying in MongoDB : There are certain query functions which are used to filter the data in the database. The two most commonly used functions are:
- find()
find() is used to get more than one single document as a result of query.
for i in mydatabase.myTable.find({title: 'MongoDB and Python' })
print (i)
|
This will output all the documents in the myTable of mydatabase whose title is ‘MongoDB and Python’.
-
count()
count() is used to get the numbers of documents with the name as passed in the parameters.
print (mydatabase.myTable.count({title: 'MongoDB and Python' }))
|
This will output the numbers of documents in the myTable of mydatabase whose title is ‘MongoDB and Python’.
These two query functions can be summed to give a give the most filtered result as shown below.
print (mydatabase.myTable.find({title: 'MongoDB and Python' }).count())
|
- To print all the documents/entries inside ‘myTable’ of database ‘mydatabase’ : Use the following code:
from pymongo import MongoClient
try :
conn = MongoClient()
print ( "Connected successfully!!!" )
except :
print ( "Could not connect to MongoDB" )
db = conn.mydatabase
collection = db.myTable
cursor = collection.find()
for record in cursor:
print (record)
|
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
28 Dec, 2022
Like Article
Save Article