MongoDB is a popular document-oriented NoSQL database that stores data in flexible JSON-like documents. With its dynamic schemas and ability to handle large volumes of unstructured data, MongoDB has become a go-to database option for modern applications.
As a developer or DBA working with MongoDB, being familiar with its common commands and queries is critical for efficiently building, managing, and querying your databases. In this comprehensive guide, we will cover the 48 most essential MongoDB commands and queries that every developer and DBA should know.
Table of Contents
- Quick Intro to MongoDB
- Basic Commands
- Check Version
- List Commands
- Get DB Stats
- Switch Databases
- List Databases
- See Current DB
- Drop a Database
- Create a Collection
- Drop a Collection
- CRUD Operations
- Insert a Document
- Find Documents
- Pretty Print Find
- Update a Document
- Delete Documents
- Distinct Values
- Indexing
- Create an Index
- List Indexes
- Drop an Index
- Data Retrieval
- Limit
- Skip
- Sort
- Validation
- Document Validation
- Schema Validation
- Check Validation
- Cursors
- Cursor Methods
- Backup and Restore
- Backup with Mongodump
- Restore from Backup
- Replication
- Configure a Replica Set
- Check Replica Set Status
- Add to Replica Set
- Step Down Primary
- Check Replication Lag
- Transactions
- Start a Transaction
- Commit a Transaction
- Handle Write Conflicts
- Profiling and Explain Plans
- Access Control
- Enable Auth
- Create a User
- Grant Roles
- Revoke Roles
- Connect from Python
Quick Intro to MongoDB
MongoDB is a document database designed to store JSON-like data without rigid schemas. Here‘s a quick rundown of some key MongoDB terminology:
-
Document – A record in a MongoDB collection, analogous to a row in a relational database table. Documents are stored in JSON format with dynamic schemas.
-
Collection – A group of MongoDB documents, like a table in a relational database.
-
Database – Contains MongoDB collections, analogous to relational databases.
-
MongoDB Shell – An interactive JavaScript interface to connect to MongoDB and execute commands.
Now let‘s get into the essential MongoDB commands developers and DBAs should know!
Basic Commands
These fundamental commands help you get started with MongoDB.
Check MongoDB Version
To check the version of mongod server and shell, use:
mongod --version
mongo --version
This verifies the installed versions match across your environment.
List Available Commands
See all available mongo shell commands with:
help()
This prints a list of methods like db.help() and db.stats().
Get Database Stats
Print statistics on collections, objects, sizes and indexes for a database with:
db.stats()
Switch Current Database
Set the current db with:
use myDatabase
This switches the shell context to myDatabase if it exists or creates it if not.
List All Databases
Print a list of databases on the server with:
show dbs
See Current Database
Print the name of the current database context in the shell session with:
db
Drop a Database
Delete an entire database including all collections and documents:
db.dropDatabase()
Make sure you switch to the correct db first!
Create a Collection
Create a new collection with:
db.createCollection("myCollection")
This will create an empty collection named myCollection in the current database visible in the shell.
Drop a Collection
Removing an entire collection with:
myCollection.drop()
All documents and indexes in that collection will be removed.
CRUD Operations
CRUD (Create, Read, Update, Delete) operations manipulate documents stored in your MongoDB databases.
Insert a Document
To insert a single document into a collection:
myCollection.insertOne({
name: "John",
age: 30
})
To insert multiple documents:
myCollection.insertMany([
{ name: "John", age: 30 },
{ name: "Jane", age: 28 }
])
MongoDB will assign _id fields automatically if not specified.
Find Documents
Retrieve documents with:
myCollection.find()
Find by condition:
myCollection.find({ age: { $gte: 18 } })
Return only one match:
myCollection.findOne({ name: "John" })
Pretty Print Find Results
Format the output from find() for easier reading:
myCollection.find().pretty()
Update a Document
Update a single document matching the filter:
myCollection.updateOne(
{ name: "John" },
{ $set: { age: 35 }}
)
Update multiple matching documents:
myCollection.updateMany(
{ age: { $lt: 30 } },
{ $set: { status: "young" }}
)
Delete Documents
Removing a single document that matches a filter condition:
myCollection.deleteOne({ name: "John" })
Deleting all documents matching a condition:
myCollection.deleteMany({ status: "inactive" })
Distinct Values
Find unique values for a field across documents:
myCollection.distinct("name")
# Returns ["John", "Jane"]
Can filter documents considered with a query.
Indexing
Indexes improve query performance by storing a sorted view of your collection‘s data.
Create an Index
Creating an ascending index on name:
myCollection.createIndex({ name: 1 })
Compound index on name and age:
myCollection.createIndex({ name: 1, age: -1 })
List Indexes
Print all indexes for a collection with:
myCollection.getIndexes()
Drop Indexes
Dropping an index by name:
myCollection.dropIndex("name_1")
Dropping all indexes:
myCollection.dropIndexes()
Data Retrieval
Controlling returned documents for efficient querying.
Limit Documents
Only return the first 10 documents:
myCollection.find().limit(10)
Skip Documents
Skip the first 10 results:
myCollection.find().skip(10)
Sort Documents
Sort by age ascending:
myCollection.find().sort({ age: 1 })
Sort by name descending:
myCollection.find().sort({ name: -1 })
Validation
Data validation ensures quality through schema validation rules.
Document Validation
Add validation rules when inserting/updating:
db.createCollection("accounts", {
validator: {
$or: [
{ balance: { $exists: true } },
{ $and: [{balance: {$gte: 0}}, {balance: {$lte: $MAX_BALANCE}}]
}]
}
})
Schema Validation
Strictly enforce schemas on insert/update:
db.runCommand({
collMod: "accounts",
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "name", "balance" ],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
balance: {
bsonType: "number",
description: "must be a number and is required"
}
}
}}
}})
Check Validation
See current validation rules:
db.getCollectionInfos({name: ‘accounts‘})
Cursors
Cursors let you iterate through query results.
Cursor Methods
Print docs using a cursor:
var myCursor = db.accounts.find()
myCursor.forEach(printjson)
while (myCursor.hasNext()) {
print(tojson(myCursor.next()))
}
Cursor bounds, limits, batch size can be set.
Backup and Restore
Essential ops for managing MongoDB data.
Backup with Mongodump
Backup data by dumping to BSON files:
mongodump --db myDb --out /opt/backup
This writes BSON files for each collection to /opt/backup.
Restore from Backup
To restore from a backup made via mongodump:
mongorestore --db newDbName /opt/backup
This loads data saved in the BSON dumps back into MongoDB.
Replication
Replication copies data across different servers.
Configure a Replica Set
Starting three mongod instances as a replica set:
mongod --replSet rs0
mongod --replSet rs0
mongod --replSet rs0
Initiating the set:
rs.initiate()
Adding members, reconfigs done on primary.
Check Replica Set Status
Print detailed status of a replica set:
rs.status()
Provides info on state, uptime, optimes, and more for secondaries and primary.
Add Node to Replica Set
Add a new member:
rs.add("mongoserver-3.com")
Once added, MongoDB will replicate data to this new secondary.
Step Down Primary
Force a secondary to become primary:
rs.stepDown(120)
After 120 secs without primary available, eligible secondaries can take over.
Check Replication Lag
Print replication lag for secondaries:
rs.printSlaveReplicationInfo()
This displays time elapsed behind primary for replicating ops.
Transactions
Atomic, consistent transactions with multi-document support.
Start a Transaction
Begin a transaction scoped to a session:
const session = db.getMongo().startSession()
session.startTransaction()
Following ops use this session until commit/abort.
Commit a Transaction
Attempts to commit ops in the transaction:
session.commitTransaction()
On error can retry commit or explicitly abort.
Handle Write Conflicts
If two concurrent operations write to the same document, one will yield:
try {
session.commitTransaction()
} catch (e) {
// Can retry commit
}
Client handles retries until commit succeeds.
Profiling and Explain Plans
Introspection into database performance.
Database Profiling
Profile a subset of operations for performance monitoring:
db.setProfilingLevel(2, { slowms: 100 })
Slow queries over 100ms will be logged to the system.profile collection.
Explain Query Plans
Inspect and debug query performance:
db.accounts.find(...).explain("executionStats")
Prints detailed stats on index use, timings, stages and more.
Access Control
Securing MongoDB authentication and authorization.
Enable Access Control
First enable auth in config file or start command:
mongod --auth
All connections now require authentication.
Create a User
Add a user:
use admin
db.createUser({
user: "appuser",
pwd: passwordPrompt(),
roles: [ "readWriteAnyDatabase" ]
})
Roles provide permissions to MongoDB resources.
Grant Roles
Assign user-defined role to a user:
db.createRole({
role: "reports",
privileges: [
{ resource: { db: "", collection: "" }, actions: ["find"] },
],
roles: []
})
db.grantRolesToUser(
"appuser",
[
{ role: "reports", db: "reporting" }
])
Revoke Roles
Remove previously granted roles:
db.revokeRolesFromUser(
"appuser",
[
{ role: "reports", db: "reporting" }
]
)
Connect from Python
Basic MongoDB connection from Python:
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["mycollection"]
doc = {"foo": "bar"}
collection.insert_one(doc)
This inserts a document and makes pymongo‘s rich API available!
Wrap Up
And there you have it – 48 of the most essential MongoDB commands and queries to boost your skills as a developer or DBA working with MongoDB databases.
With this comprehensive reference, you can efficiently create, query, manage and monitor your MongoDB environment. Master these fundamental building blocks to become a MongoDB power user!