Skip to main content

Mongo Shell Commands Quick Start

Introduction:
MongoDB is a document-oriented database, which is classified as a NoSQL database. In MongoDB, tables are called collections and records are called documents. It stores data in JSON format. The reading of data from MongoDB is fast when compared to the Relational Database.

Installation:
Install MongoDB Community Edition. Here we run MongoDB as a windows server for local development and for learning MongoDB.

After successful installation, go to the location "C:\Program Files\MongoDB\Server\4.2\bin" then run "mongod.exe" which starts MongoDB server as windows server. Uses port "27017" as default to serve the requests.

Run "mongo.exe" shell command, used as an interface to query the MongoDB.

Query Commands:

Database:
Create a new database by running the command "use your_database_name" on the "mongo.exe" shell command.

To see all the existing databases run the command "show dbs"

Collections:
To look at all Collections(Tables) in a database, first, jump to the database you want to see the collection by using the command "use your_database_name" and then run the command "show collections"  

To create a new Collection(Table), run command "db.createCollection('your_collection_name')"

Insert Document:
In mongoDB Document(Record in a table) is in  JSON format. Insert a single Document(Record in a table) run the command "db.your_collection_name.insertOne('your_json_document_data')"

Insert multiple Documents run the command "db.your_collection_name.insertMany('your_json_documets_data')"

Display OR Filter Documents:
To display all the documents in a collection run the command "db.your_collection_name.find({})"

To display document conditionally run the command "db.your_collection_name.find({your_expression})"

Update Document:
To update a single document in a collection run the command "db.your_collection_name.updateOne('your_condition','new_value')"

To update multiple documents in a collection run the command
"db.your_collection_name.updateMany('your_condition','new_value')"
"$lt:2011" check for less than 2011 extinct year

Delete Documents:
To delete a single document run the command "db.your_collection_name.deleteOne('your_condition')"
Similary to delete multiple documents run the command
"db.your_collection_name.deleteMany('your_condition')"

Comments