Basic CRUD with Command Line
MongoDB is a popular NoSQL database known for its flexibility and scalability. Performing CRUD (Create, Read, Update, Delete) operations is fundamental when working with databases. This blog post will guide you through the basic CRUD operations using the MongoDB command line interface.
Prerequisites
MongoDB installed on your machine.
MongoDB service running.
Basic understanding of command line operations.
1. Setting Up MongoDB
Before we start with CRUD operations, ensure MongoDB is installed and running on your system. To start the MongoDB server, run:
Open another terminal window and connect to the MongoDB shell:
2. Creating a Database
MongoDB uses the concept of databases and collections. To create a database, simply switch to it using the use
command. If the database does not exist, MongoDB will create it for you when you insert a document.
Output:
3. Creating a Collection
A collection in MongoDB is equivalent to a table in relational databases. To create a collection, you can use the db.createCollection()
method or insert a document directly, which will create the collection if it doesn’t exist.
Output:
4. CRUD Operations
Create
To insert documents into a collection, use the insertOne()
or insertMany()
methods.
Insert One Document:
Output:
Insert Multiple Documents:
Output:
Read
To retrieve documents from a collection, use the find()
method.
Find All Documents:
Output:
Find with Query:
Output:
Update
To modify documents in a collection, use the updateOne()
or updateMany()
methods.
Update One Document:
Output:
Update Multiple Documents:
Output:
Delete
To remove documents from a collection, use the deleteOne()
or deleteMany()
methods.
Delete One Document:
Output:
Delete Multiple Documents:
Output:
5. Conclusion
Using the MongoDB command line interface, you can easily perform basic CRUD operations. This guide covered creating a database and collection, as well as how to insert, read, update, and delete documents. These fundamental operations form the backbone of working with MongoDB, enabling you to manage and manipulate your data efficiently.
For more advanced operations and configurations, refer to the MongoDB Documentation.
Last updated