The Wayback Machine - https://web.archive.org/web/20241128000310/https://www.geeksforgeeks.org/mongodb-and-python/
Open In App

MongoDB and Python

Last Updated : 28 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 :

  1. It supports hierarchical data structure (Please refer docs for details)
  2. It supports associate arrays like Dictionaries in Python.
  3. Built-in Python drivers to connect python-application with Database. Example- PyMongo
  4. It is designed for Big Data.
  5. Deployment of MongoDB is very easy.

MongoDB vs RDBMS

Image

MongoDB and PyMongo Installation Guide

  1. First start MongoDB from command prompt using :
    Method 1:

    mongod

    or
    Method 2:

    net start MongoDB

    Image
    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

    
    

  2. 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/”)

    
    

  3. 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.

  4. 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.
    _id

  5. 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.




    # 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)

    
    

  6. 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:
    1. 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’.

    2. 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’.

    3. 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())

      
      

    4. 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")
        
      # database name: mydatabase
      db = conn.mydatabase
        
      # Created or Switched to collection names: myTable
      collection = db.myTable
        
      # To find() all the entries inside collection name 'myTable'
      cursor = collection.find()
      for record in cursor:
          print(record)

      
      



    Previous Article
    Next Article

Similar Reads

Connect MongoDB (AWS) from Local Machine using WinSCP and MongoDB Compass
Pre-requisite: AWS and MongoDB In this article, we are going to connect to the Mongo database of the AWS Ubuntu Server instance using WinSCP and learn how to get connected to the server from your local machine using MongoDB Compass.  If you haven't installed a MongoDB server in your AWS EC2 instance then follow the steps present in this article and
4 min read
MongoDB - Delete Multiple Documents Using MongoDB Shell
The db.collection.deleteMany() method is used to delete multiple documents from a collection in Mongo Shell. This method deletes multiple documents from the collection according to the filter. The deleteMany() is a Mongo shell method, which can delete multiple documents. This method can be used in multi-document transactions. If you use this method
2 min read
MongoDB Compass vs MongoDB Atlas
MongoDB is a popular NoSQL database known for flexibility and scalability. MongoDB Compass offers a graphical interface for managing databases visually while MongoDB Atlas is a cloud-based service for automated management and scaling of MongoDB databases. In this article, We will learn about the in-depth understanding of the difference between the
5 min read
MongoDB Python | Insert and Update Data
Prerequisites : MongoDB Python Basics We would first understand how to insert a document/entry in a collection of a database. Then we would work on how to update an existing document in MongoDB using pymongo library in python. The update commands helps us to update the query data inserted already in MongoDB database collection. Insert data We would
3 min read
MongoDB Python - Insert and Replace Operations
This article focus on how to replace document or entry inside a collection. We can only replace the data already inserted in the database. Prerequisites : MongoDB Python Basics Method used: replace_one() Aim: Replace entire data of old document with a new document Insertion In MongoDB We would first insert data in MongoDB. C/C++ Code # Python code
3 min read
MongoDB python | Delete Data and Drop Collection
Prerequisite : MongoDB Basics, Insert and Update Aim : To delete entries/documents of a collection in a database. Assume name of collection 'my_collection'. Method used : delete_one() or delete_many() Remove All Documents That Match a Condition : The following operation removes all documents that match the specified condition. result = my_collectio
2 min read
Web Scraping CryptoCurrency price and storing it in MongoDB using Python
Let us see how to fetch history price in USD or BTC, traded volume and market cap for a given date range using Santiment API and storing the data into MongoDB collection. Python is a mature language and getting much used in the Cryptocurrency domain. MongoDB is a NoSQL database getting paired with Python in many projects which helps to hold details
4 min read
Python MongoDB - Find
MongoDB is a cross-platform document-oriented database program and the most popular NoSQL database program. The term NoSQL means non-relational. MongoDB stores the data in the form of key-value pairs. It is an Open Source, Document Database which provides high performance and scalability along with data modeling and data management of huge sets of
3 min read
Python MongoDB - Sort
MongoDB is a cross-platform document-oriented database program and the most popular NoSQL database program. The term NoSQL means non-relational. MongoDB stores the data in the form of key-value pairs. It is an Open Source, Document Database which provides high performance and scalability along with data modeling and data management of huge sets of
2 min read
Create a database in MongoDB using Python
MongoDB is a general-purpose, document-based, distributed database built for modern application developers and the cloud. It is a document database, which means it stores data in JSON-like documents. This is an efficient way to think about data and is more expressive and powerful than the traditional table model. MongoDB has no separate command to
2 min read
3D Plotting sample Data from MongoDB Atlas Using Python
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to JSON f
3 min read
Python Mongodb - Delete_one()
Mongodb is a very popular cross-platform document-oriented, NoSQL(stands for "not only SQL") database program, written in C++. It stores data in JSON format(as key-value pairs), which makes it easy to use. MongoDB can run over multiple servers, balancing the load to keep the system up and run in case of hardware failure. Connecting to a Database St
2 min read
Python Mongodb - Delete_many()
MongoDB is a general-purpose, document-based, distributed database built for modern application developers and the cloud. It is a document database, which means it stores data in JSON-like documents. This is an efficient way to think about data and is more expressive and powerful than the traditional table model. Delete_many() Delete_many() is used
2 min read
Python MongoDB - Update_one()
MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs.First create a database on which we perform the update_one() operation: C/C++ Code # importing Mongoclient from pymongo from pymongo import MongoClient try: conn
4 min read
How to fetch data from MongoDB using Python?
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. Fetching data from MongoDB Pymongo provides various methods for fetching the data from mongodb. Let's see them one by one. 1) Find One: This method is used to fetch data
2 min read
How to access a collection in MongoDB using Python?
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. Accessing a Collection 1) Getting a list of collection: For getting a list of a MongoDB database's collections list_collection_names() method is used. This method returns
2 min read
Python MongoDB - insert_many Query
MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs. MongoDB is developed by MongoDB Inc. and was initially released on 11 February 2009. It is written in C++, Go, JavaScript, and Python languages. MongoDB offers
3 min read
Drop Collection if already exists in MongoDB using Python
Using drop() method we can drop collection if collection exists. If collection is not found then it returns False otherwise it returns True if collection is dropped. Syntax: drop() Example 1: The sample database is as follows: C/C++ Code import pymongo client = pymongo.MongoClient("mongodb://localhost:27017/") # Database name db = client[
1 min read
Python MongoDB - Update_many Query
MongoDB is a NoSQL database management system. Unlike MySQL the data in MongoDB is not stored as relations or tables. Data in mongoDB is stored as documents. Documents are Javascript/JSON like objects. More formally documents in MongoDB use BSON. PyMongo is a MongoDB API for python. It allows to read and write data from a MongoDB database using a p
3 min read
Python MongoDB - insert_one Query
MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs. MongoDB is developed by MongoDB Inc. and was initially released on 11 February 2009. It is written in C++, Go, JavaScript, and Python languages. MongoDB offers
3 min read
How to create index for MongoDB Collection using Python?
Prerequisites: MongoDB Python Basics This article focus on the create_index() method of PyMongo library. Indexes makes it efficient to perform query requests as it stores the data in a way that makes it quick & easy to traverse. Let's begin with the create_index() method: Importing PyMongo Module: Import the PyMongo module using the command:fro
2 min read
Python MongoDB - create_index Query
MongoDB is an open-source document-oriented database. MongoDB stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. Indexing Indexing helps in querying the documents efficiently. It stores the value of a specific field or set of fields which are ordered by the value of the field as specifie
2 min read
Python MongoDB - find_one_and_delete Query
MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs. Find_one_and_delete Query This function is used to delete a single document from the collection based on the filter that we pass and returns the deleted documen
2 min read
Python MongoDB - Limit Query
MongoDB is one of the most used databases with its document stored as collections. These documents can be compared to JSON objects. PyMongo is the Python driver for mongoDB. Limit() Method: The function limit() does what its name suggests- limiting the number of documents that will be returned. There is only one argument in the parameter which is a
2 min read
Python MongoDB - find_one_and_update Query
The function find_one_and_update() actually finds and updates a MongoDB document. Though default-wise this function returns the document in its original form and to return the updated document return_document has to be implemented in the code. Syntax: coll.find_one_and_update(filter, update, options) Parameters: col- collection in MongoDBfilter- cr
2 min read
Indexing in MongoDB using Python
By creating indexes in a MongoDB collection, query performance is enhanced because they store the information in such a manner that traversing it becomes easier and more efficient. There is no need for a full scan as MongoDB can search the query through indexes. Thus it restricts the number of documents that need to be checked for query criteria. S
2 min read
Python MongoDB - drop_index Query
The drop_index() library function in PyMongo is used to drop the index from a collection in the database, as the name suggests. In this article, we are going to discuss how to remove an index from a collection using our python application with PyMongo. Syntax: drop_index(index_or_name, session=None, **kwargs) Parameters: index_or_name: The name of
3 min read
Count the number of Documents in MongoDB using Python
MongoDB is a document-oriented NoSQL database that is a non-relational DB. MongoDB is a schema-free database that is based on Binary JSON format. It is organized with a group of documents (rows in RDBMS) called collection (table in RDBMS). The collections in MongoDB are schema-less. PyMongo is one of the MongoDB drivers or client libraries. Using t
2 min read
Python MongoDB - Query
MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs. What is a MongoDB Query? MongoDB query is used to specify the selection filter using query operators while retrieving the data from the collection by db.find()
3 min read
Aggregation in MongoDB using Python
MongoDB is free, open-source,cross-platform and document-oriented database management system(dbms). It is a NoSQL type of database. It store the data in BSON format on hard disk. BSON is binary form for representing simple data structure, associative array and various data types in MongoDB. NoSQL is most recently used database which provide mechani
2 min read
Practice Tags :
three90RightbarBannerImg