MongoDB is an open-source document-oriented database. Here data is stored in a document within a collection as a set of name-value pairs. It does not have a fixed structure defined at the collection level. As data is stored across multiple machines, it is horizontally scalable. It has rich query language that supports CRUD operations, aggregation, text search, and so on.
The basic building blocks are:
- Database: It contains all the data generated by the system as collections.
- Collection (Similar to Table in RDBMS): It single entity that contains all the data related to a particular aspect.
- Document (Similar to rows in RDBMS): Set of fields with associated values of corresponding datatypes.
CRUD Operations
Creating Database
use db_name is used to create the database. The command will create a new database if it doesn't exist, otherwise, it will return the existing database.
Creating Collection
db.createCollection(name) command is used to create collection.
Insert Operation
To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method, db.CollectionName.insert(document)
Read Operation
find() method will display all the documents in a non-structured way, db.CollectionName.find()
To display the results in a formatted way, you can use pretty() method, db.CollectionName.find().pretty()
RDBMS Where clause equivalents
To query the document on the basis of some conditions, you can use the following operations.
Equality - {key:{$eq:value}}
Not Equal - {key:{$ne:value}}
Less than - {key:{$lt:value}}
Less than Equals - {key:{$lte:value}}
Greater than - {key:{$gt:value}}
Greater than Equals - {key:{$gte:value}}
Update Operation
The update() method updates the values in the existing document while the save() method replaces the existing document with the document passed in the save() method.
db.CollectionName.update(selection_criteria, updated_data)
Delete Operation
MongoDB's remove() method is used to remove a document from the collection.
db.CollectionName.remove(deletion_criteria)
Thank you!! Feel free to comment on any type of feedback or error you have 😄✌
Top comments (2)
Helpful 👍
Thank you 😄