MongoDB Cheat Sheet

MongoDB Cheat Sheet

  • Orchestration
6 minute read Updated May 27, 2020

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

Pretty Print

Create Collection

Create Indexes

Create index

Create sparse index

Create compound index

Create geo index

Create partial index

Add and Delete Data

Add one data record

Add array (many) records

Delete data

Query MongoDB Documents

Search by attribute

Search by geolocation

Search greater or less than

Search not equal to

Search and return only certain fields

Search by regular expression

Find by elements in array

Replication and Sharding

Enable replication

Add shard

Show Server Memory

Aggregate functions

MapReduce

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()

Create Collection

    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 } )

Create sparse index

This does not index documents that do not have this attribute.

    db.products.createIndex({product:-1},{sparse: true})

Create compound index

    db.cars.createIndex( { make: 1 , model: -1} )

Create geo index

    db.address.createIndex( { "location": "2dsphere"} )

This indexes those documents that match the search criteria.

    db.students.createIndex(
{ age: 1},
{ partialFilterExpression: { age: { $gt: 14}}}
)

Add and Delete Data

Add one data record

Delete data

    db.cars.insert([
{
vin: 1111111111,
model: 'SK-202',
make: 'Mercedes'
}
])

Add array (many) records

    db.cars.insertMany([
{
vin: 1111111111,
model: 'SK-202',
make: 'Mercedes'
},
{
vin: 2222222,
model: 'Cabriolet',
make: 'Chevrolet' }
])

Delete data

    db.cars.remove({"make": "Chevrolet"})

Query MongoDB Documents

Query MongoDB Documents

    db.cars.find({ "make": "Mercedes"}

Search by geolocation

    db.address.find ({
location: {
$near: {
$geometry: {
type: "Point" ,
coordinates: [ -72.7738706,41.6332836 ]
},
$maxDistance: 4,
$minDistance: 0
}
}
})

Search greater or less than

    db.sales.find({"price": {$gt: 100}})

Search not equal to

    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"} )

Enable replication

Connect to a config server then:

    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")

Show Server Memory

    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()

These postings are my own and do not necessarily represent BMC's position, strategies, or opinion.

More from Orchestration

Interested in more from BMC?

The Brief is our monthly email on the mainframe and enterprise orchestration: research, customer stories, product news, events.

By registering for this offer you are confirming that you have read and agreed to BMC’s Privacy Policy.

You have subscribed to The Brief

The Brief covers the mainframe and enterprise orchestration—BMC AMI and Control-M—and the analyst research, customer deployments and events across both.