MongoDB Cheatsheet
- Authors
- Name
- xNoJustice
MongoDB Cheat Sheet
Show All Databases
show dbs
Displays a list of all available databases.
Show Current Database
db
Shows the name of the current working database.
Create Or Switch Database
use new_database
Creates a new database if it doesn't exist or switches to an existing one.
Drop Database
db.dropDatabase()
Deletes the current database.
Create Collection
db.createCollection('posts')
Creates a new collection named 'posts' in the current database.
Show Collections
show collections
Lists all collections in the current database.
Insert Row
db.posts.insert({
title: 'Post One',
body: 'Body of post one',
category: 'News',
tags: ['news', 'events'],
user: {
name: 'John Doe',
status: 'author'
},
date: Date()
})
Inserts a new document (row) into the 'posts' collection.
Insert Multiple Rows
db.posts.insertMany([
// ... multiple documents
])
Inserts multiple documents into the 'posts' collection.
Get All Rows
db.posts.find()
Retrieves all documents from the 'posts' collection.
Get All Rows Formatted
db.posts.find().pretty()
Formats and displays all documents from the 'posts' collection.
Find Rows
db.posts.find({ category: 'News' })
Retrieves documents from 'posts' where the category is 'News'.
Sort Rows
# Ascending
db.posts.find().sort({ title: 1 }).pretty()
# Descending
db.posts.find().sort({ title: -1 }).pretty()
Sorts documents based on the specified field.
Count Rows
db.posts.find().count()
db.posts.find({ category: 'news' }).count()
Counts the number of documents in the 'posts' collection.
Limit Rows
db.posts.find().limit(2).pretty()
Limits the number of retrieved documents from the 'posts' collection.
Chaining
db.posts.find().limit(2).sort({ title: 1 }).pretty()
Chains multiple operations to refine query results.
Foreach
db.posts.find().forEach(function(doc) {
print("Blog Post: " + doc.title)
})
Applies a function to each document in the 'posts' collection.
Find One Row
db.posts.findOne({ category: 'News' })
Retrieves the first document that matches the specified query.
Find Specific Fields
db.posts.find({ title: 'Post One' }, {
title: 1,
author: 1
})
Retrieves specific fields from documents in the 'posts' collection.
Update Row
db.posts.update({ title: 'Post Two' },
{
title: 'Post Two',
body: 'New body for post 2',
date: Date()
},
{
upsert: true
})
Updates or inserts a document in the 'posts' collection.
Update Specific Field
db.posts.update({ title: 'Post Two' },
{
$set: {
body: 'Body for post 2',
category: 'Technology'
}
})
Updates specific fields in a document.
Increment Field ($inc)
db.posts.update({ title: 'Post Two' },
{
$inc: {
likes: 5
}
})
Increments a numeric field in a document.
Rename Field
db.posts.update({ title: 'Post Two' },
{
$rename: {
likes: 'views'
}
})
Renames a field in a document.
Delete Row
db.posts.remove({ title: 'Post Four' })
Removes documents from the 'posts' collection based on the specified query.
Sub-Documents
db.posts.update({ title: 'Post One' },
{
$set: {
comments: [
// ... array of comments
]
}
})
Adds sub-documents (comments) to an existing document.
Find By Element in Array ($elemMatch)
db.posts.find({
comments: {
$elemMatch: {
user: 'Mary Williams'
}
}
})
Finds documents containing specific elements in an array.
Add Index
db.posts.createIndex({ title: 'text' })
Creates an index on the 'title' field for text search.
Text Search
db.posts.find({
$text: {
$search: "\"Post O\""
}
})
Performs a text search on the 'posts' collection.
Greater & Less Than
db.posts.find({ views: { $gt: 2 } })
db.posts.find({ views: { $gte: 7 } })
db.posts.find({ views: { $lt: 7 } })
db.posts.find({ views: { $lte: 7 } })
Retrieves documents with numeric values greater or less than specified.