Insert and Update Data - Python MongoDB Last Updated : 02 Jul, 2025 Comments Improve Suggest changes Like Article Like Report In MongoDB, insertion refers to adding new documents into a collection, while updating allows modifying existing documents. These operations are essential for managing dynamic datasets. With PyMongo library in Python, users can perform these tasks efficiently by establishing a connection to the database, creating or accessing collections and executing commands to insert or update data. Insert dataInserting data involves defining documents as dictionaries and adding them to a collection using insert_one() or insert_many(). Each inserted document automatically gets a unique _id field.1. Use insert_one() for a single document.collection.insert_one(doc1)Parameter: doc1 represents a dictionary2. Use insert_many() for multiple document.collection.insert_many([doc1, doc2, doc3.....])Parameter: [doc1, doc2, doc3,....] represents a list of dictionaryViewing Inserted DocumentsTo view the inserted documents, MongoDB provides the find() method, which retrieves documents from a specific collection.cursor = collection.find()for doc in cursor: print(doc)Note: find() method works only within a single collection. It does not support querying across multiple collections simultaneously.Let's see Example of Insertion of Data:- Python from pymongo import MongoClient client = MongoClient("mongodb://localhost:27017/") print("Connected successfully!") # Access database and collection db = client["mydatabase"] collection = db["my_gfg_collection"] # Documents to insert emp_rec1 = { "name": "Mr. Geek", "eid": 24, "location": "Delhi" } emp_rec2 = { "name": "Mr. Shaurya", "eid": 14, "location": "Delhi" } # Insert documents rec_id1 = collection.insert_one(emp_rec1) rec_id2 = collection.insert_one(emp_rec2) print("Data inserted with record IDs:") print("Record 1 ID:", rec_id1.inserted_id) print("Record 2 ID:", rec_id2.inserted_id) # Display inserted documents print("\nInserted records:") for record in collection.find(): print(record) OutputSnapshot of Terminal showing output of Insert DataUpdate dataUpdating data involves modifying existing documents in a collection using update_one() or update_many(). These methods require a filter to match documents and an update operation to specify the changes. With pymongo, updates can be easily applied using update operators like $set or $currentDate.1. Use update_one() to update a single matching documentcollection.update_one(filter, update)Parameter: filter a dictionary specifying the condition to match documents (e.g., {"eid": 101})update a dictionary that defines the changes to apply (e.g., {"$set": {"name": "Updated Name"}})2. Use update_many() to update all documents that match a conditioncollection.update_many(filter, update)Parameter: filter a dictionary specifying the matching criteriaupdate a dictionary with update operators and valuesCommon Update Operators1. $set: Updates the value of a specified field. If the field doesn't exist, it will be created.{"$set": {"field": "value"}}2. $currentDate: Sets the field to the current date or timestamp.{"$currentDate": {"lastModified": True}}Let's see Example of Updation of Data:- Python from pymongo import MongoClient client = MongoClient("mongodb://localhost:27017/") print("Connected successfully!") # Access database and collection db = client["mydatabase"] collection = db["my_gfg_collection"] # Update all employee documents where eid is 24 result = collection.update_many( {"eid": 24}, { "$set": { "name": "Mr. GeeksforGeeks" }, "$currentDate": { "lastModified": True } } ) # Display update result print("Matched documents:", result.matched_count) print("Modified documents:", result.modified_count) # Display all records in the collection print("\nUpdated records:") for record in collection.find(): print(record) OutputSNapshot of Terminal showing Update Data outputTo find number of documents or entries in collection that are updated, use: print(result.matched_count) Here output would be 1.Related Articles:Insert Method Update MethodLogical query operatorsComparison query operatorsProjection Operators Comment More infoAdvertise with us Next Article How to fetch data from MongoDB using Python? S shaurya uppal Follow Improve Article Tags : Technical Scripter Python Computer Organization & Architecture Python-mongoDB Practice Tags : python Similar Reads Python MongoDB Tutorial MongoDB is a popular NoSQL database designed to store and manage data flexibly and at scale. Unlike traditional relational databases that use tables and rows, MongoDB stores data as JSON-like documents using a format called BSON (Binary JSON). This document-oriented model makes it easy to handle com 2 min read Python MongoDB - IntroductionMongoDB: An introductionMongoDB is a powerful, open-source NoSQL database that offers a document-oriented data model, providing a flexible alternative to traditional relational databases. Unlike SQL databases, MongoDB stores data in BSON format, which is similar to JSON, enabling efficient and scalable data storage and ret 5 min read MongoDB and PythonMongoDB 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.Features of MongoDBIt supports hierarchical data structure.It supports associate arrays like Dictionaries in Python.Built- 3 min read Installing MongoDB on Windows with PythonThis guide will help you install and set up MongoDB on a Windows machine, along with Python integration using PyMongo. For a beginner-friendly experience, it's recommended to use an IDE like Spyder from the Anaconda distribution.Step 1: Download MongoDB Community EditionGo to the official MongoDB we 2 min read Python MongoDB - Getting StartedHow do Document Databases Work?Document databases are a powerful tool in the world of NoSQL databases, and they play an important role in modern applications, especially where flexibility, scalability, and performance are key requirements. But how exactly do document databases work? In this article, we will go deep into the struc 6 min read What is a PyMongo Cursor?MongoDB is an open-source database management system that uses the NoSql database to store large amounts of data. MongoDB uses collection and documents instead of tables like traditional relational databases. MongoDB documents are similar to JSON objects but use a variant called Binary JSON (BSON) t 2 min read Create a database in MongoDB using PythonMongoDB 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 traditiona 2 min read Python MongoDB - BasicCreate a database in MongoDB using PythonMongoDB 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 traditiona 2 min read Insert and Update Data - Python MongoDBIn MongoDB, insertion refers to adding new documents into a collection, while updating allows modifying existing documents. These operations are essential for managing dynamic datasets. With PyMongo library in Python, users can perform these tasks efficiently by establishing a connection to the data 3 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 on 2 min read Python MongoDB - MethodPython MongoDB - distinct()MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. It stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. Refer to MongoDB and Python for an in-depth introduction to the topic. N 3 min read Python MongoDB- rename()rename() method in PyMongo is used to rename a collection within a MongoDB database. It allows you to change the name of an existing collection while keeping its data intact. This is useful for reorganizing or updating collection names without losing data.Syntaxcollection.rename(new_name, dropTarget 2 min read Python MongoDB - bulk_write()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. Refer to MongoDB: An Introduction for a much more detailed introduction on MongoDB. Now let's understand the Bulk Write opera 3 min read Python MongoDB - $group (aggregation)In PyMongo, the aggregate() method processes data through a pipeline of stages to produce aggregated results. One key stage is $group, which groups documents based on a specified identifier like a field name and applies accumulator operations e.g., $sum, $avg, $max. It then outputs a new set of docu 2 min read Python MongoDB QueriesPython MongoDB - QueryMongoDB queries let you filter documents(records) using conditions. The find() method retrieves documents from a collection, and you can pass an optional query to specify which documents to return.A query is pass as a parameter to filter the results. This query uses key-value pairs and various opera 2 min read Insert and Update Data - Python MongoDBIn MongoDB, insertion refers to adding new documents into a collection, while updating allows modifying existing documents. These operations are essential for managing dynamic datasets. With PyMongo library in Python, users can perform these tasks efficiently by establishing a connection to the data 3 min read Python MongoDB - insert_one QueryMongoDB 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, 3 min read Python MongoDB - insert_many QueryIn MongoDB, insert_many() method is used to insert multiple documents into a collection at once. When working with Python, this operation is performed using the PyMongo library. Instead of inserting documents one by one with insert_one(), insert_many() allows developers to pass a list of dictionarie 2 min read Difference Between insert(), insertOne(), and insertMany() in PymongoIn PyMongo, inserting documents into a MongoDB collection can be done using different methods. Earlier versions used the insert() method, but it is now deprecated. The recommended and modern approach is to use:insert_one(): to insert a single documentinsert_many(): to insert multiple documentsThese 3 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:  Python3 # importing Mongoclient from 4 min read Python MongoDB - Update_many QueryIn PyMongo, the update_many() method is used to update multiple documents in a collection that match a given filter condition. Itâs a powerful method when you need to make bulk updates to documents based on a shared field value or pattern.Syntaxcollection.update_many(filter,update,upsert=False,array 2 min read MongoDB Python - Insert and Replace OperationsIn PyMongo, document insertion and replacement are performed using insert_one(), insert_many() and replace_one(). These methods allow you to add new documents or completely replace existing ones based on a matching filter.Syntaxcollection.insert_one(document)collection.insert_many([document1, docume 2 min read MongoDB python | Delete Data and Drop CollectionPrerequisite : 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 ma 2 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 cas 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 traditiona 2 min read Python MongoDB - FindMongoDB 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 3 min read Python MongoDB - find_one QueryIn PyMongo, the find_one() method is used to retrieve a single document from a MongoDB collection that matches the given filter. If multiple documents match, only the first match (based on insertion order) is returned.Syntaxcollection.find_one(filter, projection=None)Parameters:filter: (dict) Criter 2 min read Python MongoDB - find_one_and_update QueryThe 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, option 2 min read Python MongoDB - find_one_and_delete queryfind_one_and_delete() method in PyMongo is used to find a single document, delete it and return the deleted document. Itâs useful when you need to both remove and retrieve a document in one operation. A filter is provided to match the document and optionally a sort condition to decide which document 2 min read Python MongoDB - find_one_and_replace Queryfind_one_and_replace() method search one document if finds then replaces with the given second parameter in MongoDb. find_one_and_replace() method is differ from find_one_and_update() with the help of filter it replace the document rather than update the existing document. Syntax: find_one_and_repl 2 min read Python MongoDB - SortMongoDB 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 2 min read Python MongoDB - distinct()MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. It stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. Refer to MongoDB and Python for an in-depth introduction to the topic. N 3 min read Python MongoDB - bulk_write()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. Refer to MongoDB: An Introduction for a much more detailed introduction on MongoDB. Now let's understand the Bulk Write opera 3 min read Python MongoDB - $group (aggregation)In PyMongo, the aggregate() method processes data through a pipeline of stages to produce aggregated results. One key stage is $group, which groups documents based on a specified identifier like a field name and applies accumulator operations e.g., $sum, $avg, $max. It then outputs a new set of docu 2 min read Python MongoDB - Limit QueryMongoDB 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. Ther 2 min read Nested Queries in PyMongoMongoDB is a NoSQL document-oriented database. It does not give much importance for relations or can also be said as it is schema-free. PyMongo is a Python module that can be used to interact between the mongo database and Python applications. The data that is exchanged between the Python applicatio 3 min read Working with Collections and documents in MongoDBHow 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_coll 2 min read Get the Names of all Collections using PyMongoPyMongo is the module used for establishing a connection to the MongoDB using Python and perform all the operations like insertion, deletion, updating, etc. PyMongo is the recommended way to work with MongoDB and Python. Note: For detailed information about Python and MongoDB visit MongoDB and Pyth 2 min read Drop Collection if already exists in MongoDB using PythonUsing 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:  Python3 import pymongo client = pymongo.MongoClient("mongodb://local 1 min read How to update data in a Collection 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. Updating Data in MongoDB We can update data in a collection using update_one() method and update_many() method.  update 2 min read Get all the Documents of the Collection using PyMongoTo get all the Documents of the Collection use find() method. The find() method takes a query object as a parameter if we want to find all documents then pass none in the find() method. To include the field in the result the value of the parameter passed should be 1, if the value is 0 then it will b 1 min read Count the number of Documents in MongoDB using PythonMongoDB 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 o 2 min read Update all Documents in a Collection using PyMongoMongoDB 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. PyMongo contains tools which are used to interact with the MongoDB database. Now let's see how to update all the documents in 3 min read Aggregation in MongoDB using PythonMongoDB 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 2 min read Indexing in MongoDBIndexing in MongoDB using PythonBy 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 docum 2 min read Python MongoDB - create_index QueryMongoDB 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 whic 2 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 Modul 2 min read Get all the information of a Collection's indexes using PyMongoPrerequisites: MongoDB Python Basics This article is about displaying the information of Collection's indexes using the index_information() function of the PyMongo module. index_information() returns a dictionary where the keys are index names (as returned by create_index()) and the values are dicti 2 min read Python MongoDB - drop_index QueryThe 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 3 min read How to Drop all the indexes in a Collection using PyMongo?Prerequisites: MongoDB and Python With the help of drop_indexes() method we can drop all the indexes in a Collection. No parameter is passed in the method. Only default index _id can not be deleted. All the Non _id indexes will be the drop by this method. It means we can only drop the index which we 2 min read How to rebuild all the indexes of a collection using PyMongo?According to MongoDB documentation, normally, MongoDB compacts indexes during routine updates. For most users, the reIndex command is unnecessary. However, it may be worth running if the collection size has changed significantly or if the indexes are consuming a disproportionate amount of disk space 2 min read Conversion between MongoDB data and Structured dataHow to import JSON File in MongoDB using Python?Prerequisites: MongoDB and Python, Working With JSON Data in Python 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. JSON stands for JavaScript Object Notation 2 min read Convert PyMongo Cursor to JSONPrerequisites: MongoDB Python Basics This article is about converting the PyMongo Cursor to JSON. Functions like find() and find_one() returns the Cursor instance. Let's begin: Importing Required Modules: Import the required module using the command: from pymongo import MongoClient from bson.json_ut 2 min read Convert PyMongo Cursor to DataframePrerequisites: MongoDB Python Basics This article is about converting the PyMongo Cursor to Pandas Dataframe. Functions like find() and find_one() returns the Cursor instance. Let's begin: Importing Required Modules: Import the required module using the command: from pymongo import MongoClient from 3 min read Python MongoDB-ExerciseHow to check if the PyMongo Cursor is Empty?MongoDB is an open source NOSQL database, and is implemented in C++. It is a document oriented database implementation that stores data in structures called Collections (group of MongoDB documents). PyMongo is a famous open source library that is used for embedded MongoDB queries. PyMongo is widely 2 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 on 2 min read Geospatial Queries with Python MongoDBGeospatial data plays a crucial role in location-based applications such as mapping, navigation, logistics, and geographic data analysis. MongoDB provides robust support for geospatial queries using GeoJSON format and 2dsphere indexes, making it an excellent choice for handling location-based data e 6 min read 3D Plotting sample Data from MongoDB Atlas Using PythonMongoDB, 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 fo 3 min read Like