MongoDB
is a document-oriented, cross-platform and open-source NoSQL Database
used to store semi-structured data written in C++. Instead of tables and rows,
MongoDB stores data in key-value pairs. To make learning easy and hustle free for
developers and administrators, here are some of the frequently used MongoDB
commands.
Let’s get it started.
Basic Commands
1. Version check
The foremost command is to check the installed version of the MongoDB server and
Mongo Shell. Run this command on the terminal on Linux or CMD prompt on
windows.
mongod --version
4. Create New DB or Switch to Existing DB
This simple command help to create a new database if it doesn’t exist or help to
switch to the existing Database. In MongoDB “test” is default database hence users
use “test” DB once Mongo Shell is logged in.
use DB_Name
mongos> use geekFlareDB
switched to db geekFlareDB
Copy
5. Listing all the Databases
The mentioned command is being used to list all the databases.
show dbs
mongo> show dbs
admin 0.000GB
config 0.002GB
geekFlareDB 0.000GB
test 0.000GB
Copy
6. Check the DB currently in use
Run below command on Mongo Shell to see the DB currently in use.
db
> db
GeekFlare
Copy
7. Drop Database
The given command helps the user to drop the required database. Run the
command on MongoDB client. Please make sure to select the Database before
running the drop command. Otherwise, it will drop the default “test” Database.
db.dropDatabase()
Let's first list out all the database, switch to one of them and then drop it
> show dbs
admin 0.000GB
config 0.001GB
local 0.000GB
test 0.000GB
training 0.000GB
>
> use training
switched to db training
>
> db.dropDatabase()
{ "dropped" : "training", "ok" : 1 }
Copy
8. Create Collection
Collections are similar to tables in RDBMS.
Create a collection command consists of two parameters. The collection consists of
zero or more documents. Hence for creating a collection mandatory parameter to
use in command is its name and optional parameter might include the name of
documents, its size, and index.
Creating a simple collection.
Syntax: db.createCollection(Name,Options)
Example:
> use geekFlare
switched to db geekFlare
>
> db.createCollection("geekFlareCollection")
{ "ok" : 1 }
>
> show collections
geekFlareCollection
9. Drop Collection
Drop Collection command is similar to DDL in RDBMS. It acquires locks on the
required collection until the execution of the command. Drop collection removes the
collection from the DB along with all the indexes associated with that collection. To
drop the collection drop() method is required.
It returns true for successful drop and false in case of any error or if DB doesn’t exist.
Syntax: collectionName.drop()
Example:
> use geekFlare
switched to db geekFlare
>
> show collections
geekFlareCollection
>
> db.geekFlareCollection.drop()
true
>
> db.geekFlareCollection.drop()
false
CRUD Operations related
10. Insert Document into Collection
In MongoDB document is similar to a tuple in RDBMS.
To create a document, the insert() method is used. The insert() method creates one or
many documents in the existing collection. It also creates collection if it is not present
in DB. In MongoDB, Document is schema-less, it means there is no restriction in
inserting any number of keys in a document.
Inserting a single record
To insert one record insert() or insertOne() method can be used.
Syntax: collectionName.insertOne({document})
Example:
> db.geekFlareCollection.insertOne( {
code: "P123", Qty: 200, status: "Active"
});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ed309725429283aee2e134d")
}
Copy
Inserting multiple records
To insert many records, a list of records will be passed
to insert() or insertMany() method.
Syntax:
collectionName.insertMany([{document1},{document2},{ document3}….{ documentn}])
Example:
db.geekFlareCollection.insertMany([
... { code: "P1", Qty: 100, status: "Active"},
... { code: "P2", Qty: 200, status: "Active"},
... { code: "P3", Qty: 0, status: "Dective"}
... ]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5edf7b4e18b2c26b9dfe8cac"),
ObjectId("5edf7b4e18b2c26b9dfe8cad"),
ObjectId("5edf7b4e18b2c26b9dfe8cae")
]
}
> db.geekFlareCollection.find()
{ "_id" : ObjectId("5edf546fdfa12b33b7cb75b8"), "product" :
"bottles", "Qty" : 100 }
{ "_id" : ObjectId("5edf546fdfa12b33b7cb75b9"), "product" : "bread",
"Qty" : 20 }
{ "_id" : ObjectId("5edf546fdfa12b33b7cb75ba"), "product" :
"yogurt", "Qty" : 30 }
{ "_id" : ObjectId("5edf7b4e18b2c26b9dfe8cac"), "code" : "P1", "Qty"
: 100, "status" : "Active" }
{ "_id" : ObjectId("5edf7b4e18b2c26b9dfe8cad"), "code" : "P2", "Qty"
: 200, "status" : "Active" }
{ "_id" : ObjectId("5edf7b4e18b2c26b9dfe8cae"), "code" : "P3", "Qty"
: 0, "status" : "Dective" }
>
11. Retrieve Document from a Collection
To search for the document stored in a collection find() method can be used. The
below command will be used to retrieve all the documents from the collection.
find()method can be used to retrieve all documents stored in a collection.
Syntax: collectionName.find()
Example:
> db.geekFlareCollection.find()
{ "_id" : ObjectId("5ed31186b6f2c2bb1edb86ce"), "code" : "P1", "Qty"
: 200, "status" : "Active" }
{ "_id" : ObjectId("5ed31186b6f2c2bb1edb86cf"), "code" : "P2", "Qty"
: 200, "status" : "Active" }
{ "_id" : ObjectId("5ed31186b6f2c2bb1edb86d0"), "code" : "P3", "Qty"
: 200, "status" : "Active" }
{ "_id" : ObjectId("5ed3159eb6f2c2bb1edb86d1"), "code" : "P4", "Qty"
: 100, "status" : "Inactive" }
Copy
find({condition}) method can be used to retrieve only the required documents
based on some conditions from the collection. MongoDB provides a list
of projection and Query operators to retrieve BSON type value.
Syntax: collectionName.find({ condition })
Example:
> db.geekFlareCollection.find({ Qty: { $eq: 100 }});
{ "_id" : ObjectId("5ed3159eb6f2c2bb1edb86d1"), "code" : "P4", "Qty"
: 100, "status" : "Inactive" }
Copy
To retrieve only one document MongoDB provides the findOne() method. It
gives a formatted output.
Syntax: collectionName.findOne()
Example:
> db.geekFlareCollection.findOne();
{
"_id" : ObjectId("5ed31186b6f2c2bb1edb86ce"),
"code" : "P1",
"Qty" : 200,
"status" : "Inactive"
}
Copy
12. Beautify Retrieval output
The find() method gives a disorganized output. MongoDB provides pretty() commands
to get the formatted output.
Syntax: collectionName.find().pretty()
Example:
> db.geekFlareCollection.find({ Qty: { $eq: 100 }}).pretty();
{
"_id" : ObjectId("5ed3159eb6f2c2bb1edb86d1"),
"code" : "P4",
"Qty" : 100,
"status" : "Inactive"
}
Copy
13. Update Document in a Collection
MongoDB provides update() method to set new values for existing keys in documents.
Update command gives details of modified and matched documents. Syntax of
update command is:
Syntax: collectionName.update({KeyToUpdate},{Set Command})
Example:
> db.geekFlareCollection.find()
{ "_id" : ObjectId("5edf3f67d6bfbd8125f58cfb"), "product" :
"bottles", "Qty" : 100 }
{ "_id" : ObjectId("5edf3f67d6bfbd8125f58cfc"), "product" : "bread",
"Qty" : 20 }
{ "_id" : ObjectId("5edf3f67d6bfbd8125f58cfd"), "product" :
"yogurt", "Qty" : 30 }
>
> db.geekFlareCollection.update({"product" : "bottles"},{$set :
{"Qty": 10}} )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>
> db.geekFlareCollection.find()
{ "_id" : ObjectId("5edf3f67d6bfbd8125f58cfb"), "product" :
"bottles", "Qty" : 10 }
{ "_id" : ObjectId("5edf3f67d6bfbd8125f58cfc"), "product" : "bread",
"Qty" : 20 }
{ "_id" : ObjectId("5edf3f67d6bfbd8125f58cfd"), "product" :
"yogurt", "Qty" : 30 }
>
> db.geekFlareCollection.find()
{ "_id" : ObjectId("5edf3f67d6bfbd8125f58cfb"), "product" :
"bottles", "Qty" : 10 }
{ "_id" : ObjectId("5edf3f67d6bfbd8125f58cfc"), "product" : "bread",
"Qty" : 20 }
{ "_id" : ObjectId("5edf3f67d6bfbd8125f58cfd"), "product" :
"yogurt", "Qty" : 30 }
14. Delete Document of a Collection
To delete the document, MongoDB consist of deleteOne() and deleteMany() methods.
Syntax of delete methods are:
<strong>deleteOne({condition}) </strong>removes the single document meeting the
deletion criteria.
Syntax: collectionName.deleteOne({DeletionCondition})
Example:
> db.geekFlareCollection.deleteOne({"product" : "bread"})
{ "acknowledged" : true, "deletedCount" : 1 }
Copy
<strong>deleteMany() </strong>removes all the documents matching the deletion
criteria. Without the deletion criteria deleteMany({condition}) removes all the
documents.
Syntax: collectionName.deleteMany({DeletionCondition})
Example:
> db.geekFlareCollection.deleteMany({"product" : "bottles"})
{ "acknowledged" : true, "deletedCount" : 2 }
Copy
<strong>remove() </strong>There is another method to delete all the documents
matching the deletion criteria. remove() method takes two arguments, one is
deletion condition and the other is just one flag.
Note: Remove method is deprecated in upcoming versions.
Syntax: collectionName.remove({DeletionCondition},1)
Example:
> db.geekFlareCollection.remove({"product" : "bottles"})
WriteResult({ "nRemoved" : 1 })
Copy
15. Retrieve Distinct
The distinct() method is used to get unique records.
To get distinct records from one field.
Syntax: collectionName.distinct(field)
Example:
> db.geekFlareCollection.distinct("product")
[ "Cheese", "Snacks2", "Snacks3", "bread", "ketchup" ]
Copy
To get distinct records from one field while specifying the query.
Syntax: collectionName.distinct(field,query)
Example:
> db.geekFlareCollection.distinct('product',{"Qty":20})
[ "Snacks3", "bread" ]
Copy
16. Rename collection
MongoDB provides renameCollection () method to rename collection.
Syntax: collectionName.renameCollection(newCollectionName)
Example:
>db.geekFlareCollection.renameCollection('geekFlareCol')
{ "ok" : 1 }
> show collections
geekFlareCol