TL;DR Summary: A cheat sheet provides essential MongoDB commands for users, enhancing their ability to manage databases effectively. It covers command syntax for creating collections, indexing, data manipulation, and querying.
- Includes commands for collection management and data operations.
- Details on replication, sharding, and aggregation functions.
As part of our MongoDB Guide, we’ve compiled this cheat sheet of common and not-so-common MongoDB commands.
Table of Contents
Search and return only certain fields
Pretty Print
Add pretty() to the end of any search:
Create compound index
Create partial index
Add array (many) records
Query MongoDB Documents
Search by attribute
Search by geolocation
Search greater or less than
Search and return only certain fields
Search by regular expression
Find by elements in array
Replication and Sharding
db.collection.find({}).pretty()
db.createCollection("")
Create Indexes
Create index
The format is {attribute : sortOrder} where sort order is -1 (descending) or 1 (ascending).
db.cars.createIndex( { make: 1 } )
db.products.createIndex({product:-1},{sparse: true})
db.cars.createIndex( { make: 1 , model: -1} )
db.address.createIndex( { "location": "2dsphere"} )
This indexes those documents that match the search criteria.
db.students.createIndex(
{ age: 1},
{ partialFilterExpression: { age: { $gt: 14}}}
)
db.cars.insert([
{
vin: 1111111111,
model: 'SK-202',
make: 'Mercedes'
}
])
db.cars.insertMany([
{
vin: 1111111111,
model: 'SK-202',
make: 'Mercedes'
},
{
vin: 2222222,
model: 'Cabriolet',
make: 'Chevrolet' }
])
db.cars.remove({"make": "Chevrolet"})
db.cars.find({ "make": "Mercedes"}
db.address.find ({
location: {
$near: {
$geometry: {
type: "Point" ,
coordinates: [ -72.7738706,41.6332836 ]
},
$maxDistance: 4,
$minDistance: 0
}
}
})
db.sales.find({"price": {$gt: 100}})
db.cars.find({make: {$not: {$eq: "Mercedes"}}})
This is called projection.
Show only the make field:
db.cars.find({make: "Mercedes"}, {vin: -1})
Show every field except the make field:
db.cars.find({make: "Mercedes"}, {vin: 0})
You can use the slash or quote marks as a delimiter.
Case insensitive:
db.cars.find({"make": {$regex: /^M.*/}})
Case insensitive:
db.cars.find({"make": {$regex: /^merc.*/, $options: "i"}} )
This matches documents that contain all of these array elements:
db.manufacturers.find({"name": {$all: [ "Mercedes", "Ford" ]}} )
Match on any element in the array:
db.manufacturers.find({"name": "Ford"} )
rs.initiate()
And then show replication status:
rs.status()
Add shard
Connect to query router (mongos) server. 27018 in this example is the port number of a shard server
sh.addShard( "ShardReplSet/172.31.47.43:27018")
db.serverStatus().mem
Aggregate functions
This is the same as the SQL select count(*) from words group by word. This is the word count program.
db.words.aggregate([ {$group: { _id: "$word", cnt: {$sum: 1} } } ])
MapReduce
You can do the same word count function using the map operation:
db.words.mapReduce(
function() { emit(this.word,1); },
function(key, values) {return Array.sum(values)}, {
query:{},
} out:"total_matches"
).find()
MongoDB Guide
- MongoDB Overview: Getting Started with MongoDB
- How to Install MongoDB on Ubuntu and Mac
- Creating a Database in MongoDB
- MongoDB Shell Basic Commands
- MongoDB Compass: Using the Mongo GUI
- MongoDB Role-Based Access Control (RBAC) Explained
- MongoDB Projection & Projection Operators Explained
- MongoDB Aggregate Functions Explained
- MongoDB Sorting: sort() Method & Examples
- Using Push & Pull Operators in MongoDB
- How To Use MongoDB $unwind
- 23 Common MongoDB Query Operators & How to Use Them
- MongoDB GeoLocation Query Examples
- Introduction to MongoDB Transactions
- MongoDB Indexes: Top Index Types & How to Manage Them
- Top MongoDB Commands You Need to Know
- MongoDB Replication: A Complete Introduction
- How to Setup a MongoDB Cluster
- MongoDB Sharding: Concepts, Examples & Tutorials
- MongoDB Atlas: Setting Up & Using Managed MongoDB
- How To Run MongoDB as a Docker Container
- MongoDB Memory Usage, Management, & Requirements
- How To Use mongodump for MongoDB Backups
- Mongorestore Examples for Restoring MongoDB Backups
- How To Use PyMongo
- How to Use Mongoose for MongoDB & NodeJS
- MongoDB Cheat Sheet
- MongoDB vs Cassandra: NoSQL Databases Compared
- PostgreSQL vs MongoDB: Comparing Databases
- MySQL vs MongoDB: Comparing Databases
- MongoDB Certifications: An Introduction
These postings are my own and do not necessarily represent BMC's position, strategies, or opinion.