CRUD With MongoDB
CRUD With MongoDB
Introduction
MongoDB, a NoSQL database, supports the four fundamental operations: Create, Read, Update, and Delete,
commonly called CRUD. This article will guide you through the essential concepts and implementation of CRUD
operations using MongoDB.
We will begin by creating a dedicated database named "my-db" to serve as the focal point for all the examples
within this module. This database will act as the sandbox where we perform various CRUD operations, allowing
us to explore and understand the functionalities of MongoDB in a focused and organized manner throughout
this module.
i.e
Note - The database created i.e. “my-db” will be visible after data or collections are added.
Before diving into CRUD operations with MongoDB, ensure you have the following prerequisites
MongoDB Installed: Install MongoDB on your machine. You can find installation instructions on the official
MongoDB website
Basic knowledge of MongoDB key concept
MongoDB Shell installed: The MongoDB Shell is a command-line interface to interact with MongoDB. It's a
powerful tool for executing queries and commands directly.
MongoDB Compass installed(Optional): MongoDB Compass is a graphical user interface for MongoDB.
Though optional, it can provide a visual representation of your data and aid in understanding the operations.
Create operation
In MongoDB, data is stored in documents. Learn how to perform the Create operation using the insertOne and
insertMany methods. Dive into examples that illustrate the creation of single and multiple documents,
understanding the nuances of document structure.
In MongoDB, data in documents can be fetched using the find method. Discover how to find documents in a
collection, apply filters, limit results, and sort data. Uncover the versatility of MongoDB queries to extract
precisely the information you need.
Syntax -
Sorting documents, 1 for ascending & -1 for descending, sorting based on _id field
Updating documents allows you to modify existing data, In MongoDB, the updateOne and updateMany
methods along with the $set operator are used to modify specific fields within documents in the collections and
database.
Syntax -
Delete operation
Deleting documents removes data from a collection, In MongoDB the deleteOne and deleteMany methods are
used to delete documents within the documents inside the collection and database.
Answer - The $unset operator removes a specified field from a document. It is useful when you need to
eliminate a field or multiple fields from documents, effectively "unsetting" them.
Question 2 - How can you find documents in MongoDB where a specific field exists? Provide an example
Answer - You can use the $exists operator to find documents where a specific field exists:
This query retrieves documents where the field “name” or provided key name exists.