Introduction
MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. It provides high performance, high availability, and easy scalability. Understanding MongoDB commands is essential for managing your databases, collections, and documents effectively. This cheat sheet provides a quick reference to some of the most commonly used MongoDB commands.
MongoDB Commands Cheat Sheet
Here’s a handy cheat sheet of the most commonly used MongoDB commands, ordered by their usage and popularity:
MongoDB Command | Description |
---|---|
show dbs |
Lists all databases. |
use <db> |
Switches to the specified database. If the database does not exist, it will be created. |
show collections |
Lists all collections in the current database. |
db.createCollection('<name>') |
Creates a new collection with the specified name. |
db.<collection>.drop() |
Drops the specified collection. |
db.<collection>.insertOne(<doc>) |
Inserts a single document into the specified collection. |
db.<collection>.insertMany(<docs>) |
Inserts multiple documents into the specified collection. |
db.<collection>.find(<query>) |
Finds documents in the collection that match the query. |
db.<collection>.findOne(<query>) |
Finds a single document in the collection that matches the query. |
db.<collection>.updateOne(<query>, <update>) |
Updates a single document that matches the query. |
db.<collection>.updateMany(<query>, <update>) |
Updates multiple documents that match the query. |
db.<collection>.replaceOne(<query>, <replacement>) |
Replaces a single document that matches the query. |
db.<collection>.deleteOne(<query>) |
Deletes a single document that matches the query. |
db.<collection>.deleteMany(<query>) |
Deletes multiple documents that match the query. |
db.<collection>.countDocuments(<query>) |
Counts the number of documents that match the query. |
db.<collection>.aggregate(<pipeline>) |
Performs aggregation operations using the specified pipeline. |
db.<collection>.createIndex(<keys>, <options>) |
Creates an index on the specified keys with the given options. |
db.<collection>.getIndexes() |
Lists all indexes on the collection. |
db.<collection>.dropIndex('<index_name>') |
Drops the specified index from the collection. |
db.stats() |
Provides statistics about the current database. |
db.<collection>.stats() |
Provides statistics about the specified collection. |
db.serverStatus() |
Returns an overview of the database’s state. |
db.currentOp() |
Displays the currently running operations in the database. |
db.killOp(<opId>) |
Terminates a running operation. |
db.adminCommand({shutdown: 1}) |
Shuts down the MongoDB server. |
db.runCommand(<command>) |
Runs a database command directly. |
mongo --version |
Displays the MongoDB shell version. |
mongo <script.js> |
Executes a JavaScript file in the MongoDB shell. |
mongodump --db <db> --out <directory> |
Creates a binary backup of the specified database. |
mongorestore --db <db> <directory> |
Restores a database from a binary backup. |
mongoexport --db <db> --collection <collection> --out <file> |
Exports data from a collection to a JSON or CSV file. |
mongoimport --db <db> --collection <collection> --file <file> |
Imports data from a JSON or CSV file to a collection. |
Explanation of Key Commands with Examples
show dbs
Description: Lists all databases.
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
Explanation: This command displays all the databases available on the MongoDB server.
use <db>
Description: Switches to the specified database. If the database does not exist, it will be created.
> use myDatabase
switched to db myDatabase
Explanation: This command switches the context to myDatabase
. If myDatabase
does not exist, it will be created.
show collections
Description: Lists all collections in the current database.
> show collections
myCollection
Explanation: This command lists all the collections in the currently selected database.
db.createCollection(‘<name>’)
Description: Creates a new collection with the specified name.
> db.createCollection('myCollection')
{ "ok" : 1 }
Explanation: This command creates a new collection named myCollection
in the current database.
db.<collection>.drop()
Description: Drops the specified collection.
> db.myCollection.drop()
true
Explanation: This command deletes the myCollection
collection from the current database.
db.<collection>.insertOne(<doc>)
Description: Inserts a single document into the specified collection.
> db.myCollection.insertOne({ name: "John", age: 30 })
{
"acknowledged" : true,
"insertedId" : ObjectId("60d5ecb61d1e4a5b40a733c4")
}
Explanation: This command inserts one document into myCollection
.
db.<collection>.insertMany(<docs>)
Description: Inserts multiple documents into the specified collection.
> db.myCollection.insertMany([
{ name: "John", age: 30 },
{ name: "Jane", age: 25 }
])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("60d5ecd91d1e4a5b40a733c5"),
ObjectId("60d5ecd91d1e4a5b40a733c6")
]
}
Explanation: This command inserts multiple documents into myCollection
.
db.<collection>.find(<query>)
Description: Finds documents in the collection that match the query.
> db.myCollection.find({ age: { $gt: 25 } })
{ "_id" : ObjectId("60d5ecb61d1e4a5b40a733c4"), "name" : "John", "age" : 30 }
Explanation: This command finds all documents in myCollection
where the age is greater than 25.
db.<collection>.findOne(<query>)
Description: Finds a single document in the collection that matches the query.
> db.myCollection.findOne({ name: "John" })
{ "_id" : ObjectId("60d5ecb61d1e4a5b40a733c4"), "name" : "John", "age" : 30 }
Explanation: This command finds one document in myCollection
where the name is “John”.
db.<collection>.updateOne(<query>, <update>)
Description: Updates a single document that matches the query.
> db.myCollection.updateOne({ name: "John" }, { $set: { age: 31 } })
{
"acknowledged" : true,
"matchedCount" : 1,
"modifiedCount" : 1
}
Explanation: This command updates one document in myCollection
where the name is “John” by setting the age to 31.
db.<collection>.updateMany(<query>, <update>)
Description: Updates multiple documents that match the query.
> db.myCollection.updateMany({ age: { $gt: 25 } }, { $set: { status: "Senior" } })
{
"acknowledged" : true,
"matchedCount" : 2,
"modifiedCount" : 2
}
Explanation: This command updates all documents in myCollection
where the age is greater than 25, setting the status to “Senior”.
db.<collection>.replaceOne(<query>, <replacement>)
Description: Replaces a single document that matches the query.
> db.myCollection.replaceOne({ name: "John" }, { name: "Johnny", age: 31 })
{
"acknowledged" : true,
"matchedCount" : 1,
"modifiedCount" : 1
}
Explanation: This command replaces the document in myCollection
where the name is “John” with a new document.
db.<collection>.deleteOne(<query>)
Description: Deletes a single document that matches the query.
> db.myCollection.deleteOne({ name: "John" })
{ "acknowledged" : true, "deletedCount" : 1 }
Explanation: This command deletes one document from myCollection
where the name is “John”.
db.<collection>.deleteMany(<query>)
Description: Deletes multiple documents that match the query.
> db.myCollection.deleteMany({ age: { $lt: 30 } })
{ "acknowledged" : true, "deletedCount" : 1 }
Explanation: This command deletes all documents from myCollection
where the age is less than 30.
db.<collection>.countDocuments(<query>)
Description: Counts the number of documents that match the query.
> db.myCollection.countDocuments({ age: { $gt: 25 } })
2
Explanation: This command counts the number of documents in myCollection
where the age is greater than 25.
db.<collection>.aggregate(<pipeline>)
Description: Performs aggregation operations using the specified pipeline.
> db.myCollection.aggregate([
{ $match: { status: "Senior" } },
{ $group: { _id: "$age", total: { $sum: 1 } } }
])
{ "_id" : 31, "total" : 2 }
Explanation: This command aggregates the documents in myCollection
that have the status “Senior” and groups them by age, counting the total number.
db.<collection>.createIndex(<keys>, <options>)
Description: Creates an index on the specified keys with the given options.
> db.myCollection.createIndex({ name: 1 }, { unique: true })
"name_1"
Explanation: This command creates a unique index on the name
field in myCollection
.
db.<collection>.getIndexes()
Description: Lists all indexes on the collection.
> db.myCollection.getIndexes()
[
{
"v" : 2,
"key" : { "_id" : 1 },
"name" : "_id_",
"ns" : "myDatabase.myCollection"
},
{
"v" : 2,
"key" : { "name" : 1 },
"name" : "name_1",
"ns" : "myDatabase.myCollection",
"unique" : true
}
]
Explanation: This command lists all the indexes on myCollection
.
db.<collection>.dropIndex(‘<index_name>’)
Description: Drops the specified index from the collection.
> db.myCollection.dropIndex("name_1")
{ "nIndexesWas" : 2, "ok" : 1 }
Explanation: This command drops the index named name_1
from myCollection
.
db.stats()
Description: Provides statistics about the current database.
> db.stats()
{
"db" : "myDatabase",
"collections" : 1,
"views" : 0,
"objects" : 2,
"avgObjSize" : 67,
"dataSize" : 134,
"storageSize" : 16384,
"indexes" : 1,
"indexSize" : 16384,
"ok" : 1
}
Explanation: This command provides statistics about the current database, including the number of collections, objects, and indexes.
db.<collection>.stats()
Description: Provides statistics about the specified collection.
> db.myCollection.stats()
{
"ns" : "myDatabase.myCollection",
"size" : 134,
"count" : 2,
"avgObjSize" : 67,
"storageSize" : 16384,
"nindexes" : 1,
"totalIndexSize" : 16384,
"indexSizes" : { "_id_" : 16384 },
"ok" : 1
}
Explanation: This command provides statistics about myCollection
, including its size, object count, and index sizes.
db.serverStatus()
Description: Returns an overview of the database’s state.
> db.serverStatus()
{
"host" : "myHost",
"version" : "4.4.4",
"process" : "mongod",
"uptime" : 12345,
// more fields...
}
Explanation: This command returns an overview of the MongoDB server’s state, including version, uptime, and other metrics.
db.currentOp()
Description: Displays the currently running operations in the database.
> db.currentOp()
{
"inprog" : [
{
"opid" : 12345,
"active" : true,
"secs_running" : 10,
"microsecs_running" : NumberLong(10000000),
"op" : "query",
"ns" : "myDatabase.myCollection",
// more fields...
}
]
}
Explanation: This command displays information about the currently running operations in the MongoDB server.
db.killOp(<opId>)
Description: Terminates a running operation.
> db.killOp(12345)
{ "ok" : 1 }
Explanation: This command terminates the running operation with the specified opId
.
db.adminCommand({shutdown: 1})
Description: Shuts down the MongoDB server.
> db.adminCommand({ shutdown: 1 })
server should be down...
Explanation: This command shuts down the MongoDB server.
db.runCommand(<command>)
Description: Runs a database command directly.
> db.runCommand({ ping: 1 })
{ "ok" : 1 }
Explanation: This command runs the ping
command, which checks the connection to the MongoDB server.
mongo –version
Description: Displays the MongoDB shell version.
> mongo --version
MongoDB shell version v4.4.4
Explanation: This command displays the version of the MongoDB shell.
mongo <script.js>
Description: Executes a JavaScript file in the MongoDB shell.
> mongo myScript.js
Explanation: This command executes the JavaScript file myScript.js
in the MongoDB shell.
mongodump –db <db> –out <directory>
Description: Creates a binary backup of the specified database.
> mongodump --db myDatabase --out /backup/
Explanation: This command creates a binary backup of myDatabase
in the /backup/
directory.
mongorestore –db <db> <directory>
Description: Restores a database from a binary backup.
> mongorestore --db myDatabase /backup/myDatabase
Explanation: This command restores myDatabase
from the backup located in /backup/myDatabase
.
mongoexport –db <db> –collection <collection> –out <file>
Description: Exports data from a collection to a JSON or CSV file.
> mongoexport --db myDatabase --collection myCollection --out myCollection.json
Explanation: This command exports the data from myCollection
in myDatabase
to myCollection.json
.
mongoimport –db <db> –collection <collection> –file <file>
Description: Imports data from a JSON or CSV file to a collection.
> mongoimport --db myDatabase --collection myCollection --file myCollection.json
Explanation: This command imports the data from myCollection.json
into myCollection
in myDatabase
.
Conclusion
Mastering MongoDB commands is essential for managing your NoSQL databases effectively. This cheat sheet provides a quick reference to some of the most commonly used MongoDB commands, helping you streamline your database operations and improve your productivity. By understanding and using these commands, you can simplify your data management processes, enhance your efficiency, and ensure your databases are well-maintained. Keep this guide handy to make the most of MongoDB. Happy coding!