Our Data Engineering Byte Newsletter gives data engineers and practitioners what they often lack today: clear, real-world insights—where every byte tells a story.Subscribe here to stay ahead in data engineeringIntroductionCRUD operations form the backbone of how developers interact with MongoDB databases. Whether you're building a small prototype or scaling a production application, understanding how to create, read, update, and delete data is essential. These four operations allow developers to insert new documents, retrieve existing information, modify stored data, and remove records when they are no longer needed.In MongoDB, CRUD operations can be performed using different tools and programming environments. Developers often begin with mongosh (MongoDB Shell) for direct database interaction and testing queries, while application development typically uses official drivers such as PyMongo for Python. This excerpt introduces the core CRUD concepts and demonstrates how to perform them using both mongosh and the MongoDB Python driver, helping developers understand the fundamental workflows for managing data in MongoDB.MongoDB CRUD operationsCRUD operations are the foundation of interacting with a MongoDB deployment. These operations require you to connect to the MongoDB server before you can query the relevant documents, adjust the specified properties, and subsequently, transmit the data back to the database for updates. Each CRUD operation serves a distinct purpose:The create operation creates and inserts new documents into the databaseThe read operation queries a document or documents in the databaseThe update operation modifies existing documents in the databaseThe delete operation removes documents from the databaseBasic CRUD with mongoshmongosh, also known as the MongoDB Shell, is an environment for hosting MongoDB deployments. It is equivalent to the administration console that relational databases use. You can download mongosh at https://www.mongodb.com/docs/mongodb-shell/install/.This section explains how to connect to your deployment with mongosh, insert a document into a database, query your database for a specified document, update a document, and delete a document. For more in-depth information and examples, you can also refer to the CRUD operations section of the MongoDB database manual at https://www.mongodb.com/docs/manual/crud/.Connecting to MongoDBBefore you can perform CRUD operations, you must connect to your MongoDB deployment. To connect to mongosh, you must specify your deployment connection string as well as any specified parameters.For example, enter a variation of the following code block in your terminal to connect to a MongoDB deployment with mongosh:mongosh "mongodb+srv://mycluster.packt.mongodb.net/myDatabase" --username myUsername --password myPasswordCreating documentsTo create a document in mongosh, you can use the db.collection.insertOne() command. This mongosh command creates a new document and inserts the created document into the specified collection.For example, the following db.collection.insertOne()command creates and inserts a new document into the library collection of the database. The new document has a title field set to Mastering MongoDB 8.0 and an isbn field set to 101:db.library.insertOne(
{ title: 'Mastering MongoDB 8.0', isbn: '101' } )When you successfully create and insert a document, MongoDB returns a confirmation output that contains the ObjectID value of the new document:{ acknowledged: true,
insertedId: ObjectId("652024e7ab44f3bf77788a3d")
}You can also use the following mongosh commands to update documents:db.collection.insertMany()db.collection.updateOne() with the upsert: true optiondb.collection.updateMany() with the upsert: true optiondb.collection.findAndModify() with the upsert: true optiondb.collection.findOneAndUpdate() with the upsert: true optiondb.collection.findOneAndReplace() with the upsert: true optionReading documentsRead operations in MongoDB are also called queries. To perform a basic read operation, or query, for a single document, use the db.collection.findOne() method and specify the selection criteria of the document that you want to read.For example, the following operation queries for a document in the library collection that contains the isbn field value of 101:db.library.find( { isbn: '101' } )If the library collection contains a document that matches your specified selection criteria, MongoDB returns an array that contains the document that matches:[ {
_id: ObjectId("652024e7ab44f3bf77788a3d"), title: 'Mastering MongoDB 8.0', isbn: '101'
} ]You can also use the following mongosh commands to read documents:db.collection.findOne()Updating documentsTo update a document, you can use the db.collection.updateOne() command. This command finds a document that matches the specified criteria and updates the found document.For example, the following code finds the document in the library collection that has an isbn field value of 101 and updates that document so that it contains a price field with a value of 30:db.library.updateOne( { isbn: '101' }, { $set: { price: 30 } } )When you successfully update a document, MongoDB returns the following confirmation summary:{
acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0
}You can also use the following mongosh commands to update documents:db.collection.updateMany()db.collection.replaceOne()db.collection.findOneAndReplace()db.collection.findOneAndUpdate()db.collection.findAndModify()MongoDB 8.0 also introduces the ability to sort documents within an update operation. If you specify a sort parameter in an operation that uses db.collection.updateOne(), db.collection. replaceOne(), or update, MongoDB sorts documents before updating to be able to select a specific document for the operation when multiple documents match the query.For example, the following update operation sorts all books by price and updates the lowest price book to be on sale for 25% off:db.library.updateOne(
{ },
[
{ $set: { price: { $multiply: ["$price", 0.75] } } }
],
{ sort: { price: 1 } }
)Deleting documentsTo delete a document, you can use the db.collection.deleteOne() command. This command queries for a document that matches specified criteria and deletes the found document.For example, the following operation deletes a document in the library collection that has an isbn field value of 101:db.library.deleteOne( { isbn: '101' } )When you successfully delete a document, MongoDB returns the following output:{ acknowledged: true, deletedCount: 1
}You can also use the following mongosh commands to delete documents:db.collection.deleteMany()db.collection.remove()db.collection.findOneAndDelete()db.collection.findAndModify()Basic CRUD with the Python driverAs an alternative to mongosh, MongoDB provides official drivers to interact with your MongoDB deployment. For a full list of official MongoDB driver libraries, see https://www.mongodb.com/ docs/drivers/.The following sections walk you through performing CRUD operations with the MongoDB Python driver, PyMongo. PyMongo provides a seamless bridge between the dynamic world of Python programming and the efficient, document-oriented NoSQL database of MongoDB.Installing and connecting to PyMongoYou can use pip to install PyMongo. You must have Python installed prior to installing PyMongo.For example, the following operation installs PyMongo through your terminal:To connect to your MongoDB deployment with PyMongo, you must use your connection string.For example, the following code snippet in a .py file connects to a MongoDB deployment:from pymongo import MongoClient uri = "<connection string>"
client = MongoClient(uri)
try:
client.admin.command('ping')
print("Pinged your deployment. You successfully connected to
MongoDB!")
except Exception as e: print(e)If you run the preceding code in a .py file and successfully connect to your deployment, MongoDB returns the following confirmation:"Pinged your deployment. You successfully connected to MongoDB!"You can test your connection to your MongoDB deployment on Atlas with the following code block in a .py file. This code block uses the asyncio asynchronous framework:import asyncio from motor.motor_asyncio import AsyncIOMotorClient from pymongo.server_api import ServerApi
async def ping_server():
uri = "<connection string>" client = AsyncIOMotorClient(uri, server_api=ServerApi('1'))
try:
await client.admin.command('ping')
print("Pinged your deployment. You successfully connected to MongoDB!") except Exception as e: print(e) asyncio.run(ping_server())If you run the preceding code in a .py file and successfully connect to your deployment, MongoDB returns the following confirmation:"Pinged your deployment. You successfully connected to MongoDB!".Creating documentsTo create and insert documents with PyMongo, use the insert_one command.For example, the code block that follows performs the following operations:Specifies the library collection within the resources databaseDefines a new document that represents a book titled Python and MongoDBInserts the new document into the library databasePrints the ObjectId value of the new documentlibrary = client.resources.library
book = { 'isbn': '301',
'name': 'Python and MongoDB',
'meta': {'version': 'MongoDB 8.0'},
'price': 60
}
insert_result = library.insert_one(book) print(insert_result)If you successfully insert a document with this script, MongoDB prints the ObjectId value of the inserted document.Reading documentsYou can read documents from your database with queries.To read a document, specify the condition(s) of the document you want to read with a find_onecommand.For example, the code block that follows performs the following actions:Specifies the library collection in the resources databaseFinds documents with the name value of Python and MongoDB Prints the found documentlibrary = client.resources.library
result = library.find_one( {"name": "Python and MongoDB"} ) print (result)Updating documentsTo update a document with PyMongo, use the update_one command. This command finds a document based on specified criteria and updates the found document.For example, the code block that follows performs the following operations:Finds the document where the name field is Advanced MongoDB TechniquesSets the price field of the found document to the value of 75Prints the result of the update_one operation Prints the updated documentupdate_result = library.update_one( { "name": "Advanced MongoDB Techniques"},
{ "$set": { "price": 75 } }
)
print(update_result.raw_result)
updated_document = library.find_one( {"name": "Advanced MongoDB Techniques"}
)
print(updated_document)Deleting a documentTo delete a document with PyMongo, use the delete_one command. For example, the code block that follows performs the following operations:Specifies the isbn value of the book to delete as 303Uses the delete_one command to delete a book from the library collection with the desired isbn valuePrints the result of the delete_one operationisbn_to_delete = '303'
delete_result = library.delete_one({"isbn": isbn_to_delete})
print(delete_result.raw_result)If the operation successfully deleted the desired document, MongoDB returns the following confirmation:{'n': 1, 'ok': 1.0}The n value indicates the number of documents that MongoDB deleted. In this case, MongoDB deleted one document. The ok value indicates whether the operation caused any errors. The 1.0 value in the preceding confirmation signifies that MongoDB did not encounter an error with this operation.ConclusionCRUD operations are the fundamental building blocks for working with MongoDB. By learning how to connect to a MongoDB deployment and perform create, read, update, and delete operations, developers gain the ability to manage application data efficiently. Tools such as mongosh provide a powerful command-line environment for direct database interaction, while drivers like PyMongo allow seamless integration between MongoDB and programming languages such as Python. Together, these tools enable developers to prototype, test, and build robust data-driven applications.This section provides a practical overview of MongoDB CRUD workflows, illustrating how documents can be inserted, queried, modified, and removed using both the MongoDB Shell and the Python driver.This content is an excerpt from The Official MongoDB Guide, published by Packt and MongoDB, and written by Rachelle Palmer, Jeffrey Allen, Parker Faucher, Alison Huh, Lander Kerbey, Maya Raman, and Lauren Tran.Author BioRachelle Palmer is the Product Leader for Developer Database Experience and Developer Education at MongoDB, overseeing the driver client libraries, documentation, framework integrations, and MongoDB University. She has built sample applications for MongoDB in Java, PHP, Rust, Python, Node.js, and Ruby. Rachelle joined MongoDB in 2013 and was previously the Director of the Technical Services Engineering team, creating and managing the team that provided support and CloudOps to MongoDB Atlas.Jeffery Allen is a Technical Writer at MongoDB, based in the New York City area. He focuses on server documentation and works closely with Product and Engineering teams to develop examples that reflect real-world use cases, especially pertaining to data modeling and the MongoDB query language. Before joining MongoDB, Jeff worked as a full-stack web developer. Jeff also enjoys playing guitar and piano and produces electronic music in his spare time.Parker Faucher is a self-taught Software Engineer with over six years of experience in technical education. He has authored more than 100 educational videos for MongoDB, establishing himself as a knowledgeable resource in database technologies. Currently, Parker focuses on Artificial Intelligence and Search technologies, exploring innovative solutions in these rapidly evolving fields. hen not advancing his technical expertise, Parker enjoys spending quality time with his family and maintains an avid interest in collecting comic books.Lander Kerbey is a Technical Writer at MongoDB, specializing in Atlas Stream Processing. Prior to MongoDB, he worked at InterSystems, documenting various parts of the HealthShare suite, along with their various data analytics tools. His 11 years of experience as an educator informs his approach to documentation, as he strives to create “Aha!” moments for users.Maya Raman is a Technical Writer and sometimes-software engineer at MongoDB. She is passionate about the intersections between the environment, art and literature, technology, and people. She is based in New York City and likes to spend her time hanging out in Prospect Park, even in winter.Lauren Tran is a Technical Writer at MongoDB with a background in Communications and Computer Science. She is on the Server Documentation team and mainly specializes in Information Architecture, Time Series data, and Search. Lauren is passionate about creating accessible and inclusive documentation that caters to diverse audiences. She is based in Chicago following four years in New York City and in her free time, enjoys reading on the beach at Lake Michigan and listening to Taylor Swift music.
Read more
Rachelle Palmer, Jeffrey Allen, Parker Faucher, Alison Huh, Lander Kerbey, Maya Raman, and Lauren Tran
16 Mar 2026