Hello everyone! In my previous blog I explained about what is MongoDB and why we need to go with it you can find in this blog.
In this blog, I will try to explain CRUD operations on MongoDB using MongoShell.
- To check available database:-
This command will show you a list of all available database.
- To create a database in MongoDB:- By using the command given below, you can switch to the new database.
Here DATABASE_NAME is representing your database name which you want to create
- To check the current database : –
- To create a collection in database:- In the command given below, db is the reference to the database that you are correctly using.
- To check available collection:-
- To Insert a document in a collection:- MongoDB provides the following methods to insert documents into a collection.
- To insert one document:-
2. To insert many documents:-
Here you can see we inserted two documents at a time and it returns the acknowledgment of inserted document. You also noticed that it returns _id which is the unique id that is set by MongoDB. You can read more about the primary key(_id) in my previous blog.
- To retrieve all data from the collection:-
- To retrieve the data that satisfy the condition:-
In the example given below, the condition applied is: name should be “shubham”
- Retrieve only one document:- Returns one document that satisfies the specified query criteria on the collection or view. If multiple documents satisfy the query, this method returns the first document according to the natural order which reflects the order of documents on the disk
- To update a document:- MongoDB uses the update() method for updating its document that accepts two arguments.
1. A document in which you need to define the condition for updating the document.
2. A document which contains the fields which need to be updated.
Notice: When the updated condition that meets more than one document then MongoDB updates only one document. For updating all the documents that satisfy the condition, you have to set the value of the field multi as true.
- To remove document in MongoDB: Removes all documents from the collection.
- To remove document by condition:-
Hope this blog helps you to do some basic operations on MongoDB. In my next blog, I will explain more operations like sorting, aggregation etc. so we will meet soon with another blog 🙂