MongoDB Cheat Sheet Red Hat Developer
MongoDB Cheat Sheet Red Hat Developer
Cheat sheet
MongoDB
MongoDB is a NoSQL, document-centric database. MongoDB is intended to be used small and enterprise grade
projects that need a document-centric database solution that scales up on demand.
The following sections describe the command and tasks that are basic to using MongoDB.
The $$ symbol in the examples below represents the console prompt for a terminal window.
The >> symbol in the examples below represents the Mongo shell prompt.
The following sections describe commands to access the Mongo shell from a terminal window.
mongo
Example:
show dbs
Example:
admin 0.000GB
config 0.000GB
fruit 0.000GB
local 0.000GB
use <database_name>
Example:
switched to db fruit
show collections
Example:
apples
oranges
countries
developers.redhat.com redhat-developer @rhdevelopers
Example:
{
"role" : "enableSharding",
"db" : "test",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "dbOwner",
"db" : "test",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "dbAdmin",
"db" : "test",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "userAdmin",
"db" : "test",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "read",
"db" : "test",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "readWrite",
"db" : "test",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
The following sections show you now to create a user, delete a user and list users in a given database.
developers.redhat.com redhat-developer @rhdevelopers
Create user
db.runCommand(createUser <username> . . . . )
Example:
db.runCommand(
{
createUser: "cooluser",
pwd: "newpassword",
roles: [
{ role: "readWrite", db: "fruit" }
]
})
{ "ok" : 1 }
Show users
show users
Example:
{
"_id" : "fruit.cooluser",
"userId" : UUID("78e368a7-dff0-45be-8633-f3d63802ca93"),
"user" : "cooluser",
"db" : "fruit",
"roles" : [
{
"role" : "readWrite",
"db" : "fruit"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
Delete user
db.dropUser("<user_name>")
Example:
developers.redhat.com redhat-developer @rhdevelopers
> db.dropUser("cooluser")
true
Or
A collection is an array of documents that exist within a given database. You can think of a document as a NoSQL
record.
The following sections show you how to create and delete a collection in a given database as well as how to list
collections in a given database.
Create a collection
db.createCollection(<collection_name>)
Example:
> db.createCollection("pears")
{ "ok" : 1 }
show collections
Example:
apples
oranges
pears
developers.redhat.com redhat-developer @rhdevelopers
Delete a collection
db.<collection_name>.drop()
Example:
> db.pears.drop()
true
The following sections show you how perform basic queries against a given collection in a database.
db.<collection_name>.find()
db.["<collection_name>"].find()
Example:
> db["apples"].find()
Or
developers.redhat.com redhat-developer @rhdevelopers
> db.apples.find()
Where <sort_order>
<sort_order> is 1, the documents will be listed in ascending order; -1 indicates descending order.
Example:
The following example shows how to sort all documents in ascending order first sorting on countryOfOrigin
countryOfOrigin and then
sorting on price:
price
db.<collection_name>.findOne()
Example:
> db.apples.findOne()
{
"_id" : ObjectId("627d9053f7e6008a00844a81"),
"type" : "granny smith",
"price" : 2.99,
"countryOfOrigin" : "USA"
}
Example:
db.<collection_name>.findOne({<query:criteria>})
Example:
Example:
The following sections describe how to update and remove existing documents in a given database.
db.<collection_name>.insert({ <document_declaration_in_json>})
Example:
db.<collection_name>.remove(<deletion_criteria>)
developers.redhat.com redhat-developer @rhdevelopers
Example:
db.<collection_name>.remove(<deletion_criteria>)
Example:
You can use a variable to store the results of a query. Once the result is stored, the variable can be used to modify
data within the variable. A variable provides a shorthand for working with data.
Example:
> crabapple
{
"_id" : ObjectId("627ea4c10d8bd2fbf249eae7"),
"type" : "crab",
"price" : 0.09,
"countryOfOrigin" : "Canada"
}
Example:
> usa
{ "_id" : ObjectId("627ea4c10d8bd2fbf249eadf"), "type" : "granny smith",
"price" : 2.99, "countryOfOrigin" : "USA" }
{ "_id" : ObjectId("627ea4c10d8bd2fbf249eae1"), "type" : "gala", "price" :
1.29, "countryOfOrigin" : "USA" }
{ "_id" : ObjectId("627ea4c10d8bd2fbf249eae2"), "type" : "empire",
"price" : 1.59, "countryOfOrigin" : "USA" }
{ "_id" : ObjectId("627ea4c10d8bd2fbf249eae3"), "type" : "delicious",
"price" : 1.59, "countryOfOrigin" : "USA" }
{ "_id" : ObjectId("627ea4c10d8bd2fbf249eae4"), "type" : "macintosh",
"price" : 0.99, "countryOfOrigin" : "USA" }
>
You can make changes in data assigned to a variable and then persist that data by saving the variable.
Example:
> db.apples.save(crabapple)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
An index is a digest of the data in a Mongo database. If an index does not exist in the database, then Mongo scans
every document in the given collection in order to select those documents that match the query statement. The
efficiency of using an index is apparent.
A database can have any number of indexes. Indexes are created and removed according to a particular property in
the documents.
developers.redhat.com redhat-developer @rhdevelopers
Get indexes
db.<collection_name>.getIndexes()
Example:
> db.apples.getIndexes()
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" } ]
Add an index
db.<collection_name>.createIndex(<field_name>, <sort_order>)
When <sort_order>
<sort_order> is 1, order is ascending. A <sort_order>
<sort_order> of -1 is descending order.
Example:
{
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"createdCollectionAutomatically" : false,
"ok" : 1
}
Drop an index
Drop an index according to the field name upon which index as created:
Aggregation
Aggregation is the capability to combine two collections together using a single query to create a single result set.
> db.apples.aggregate([
{$match:{ countryOfOrigin: "Mexico" }},
{ $lookup:
{
from: "countries",
localField: "countryOfOrigin",
foreignField: "country",
as: "regional_info"
}
}
]).pretty()
{
"_id" : ObjectId("627efc53a96c699c93564740"),
"type" : "golden delicious",
"price" : 0.99,
"countryOfOrigin" : "Mexico",
"regional_info" : [
{
"_id" : ObjectId("627efc54bb142679f4604979"),
"country" : "Mexico",
"continent" : "North America"
}
]
}
Dangerous tasks
The following sections describe tasks that need to be executed with care.
db.<collection_name>.drop()
Example:
> db.apples.drop()
<database>.dropDatabase()
developers.redhat.com redhat-developer @rhdevelopers
Example:
> db.dropDatabase()
{ "ok" : 1 }
Don’t do this:
The following replaces the entire document, removing all fields except price:
price
Example:
> db.apples.find()
Do this:
> db.apples.find()
{ "_id" : ObjectId("627ec9c81a9f54fbff86f145"), "type" : "granny smith",
"price" : 2.49, "countryOfOrigin" : "USA" }
{ "_id" : ObjectId("627ec9c81a9f54fbff86f146"), "type" : "golden
delicious", "price" : 0.99, "countryOfOrigin" : "Ireland" }
{ "_id" : ObjectId("627ec9c81a9f54fbff86f147"), "type" : "gala", "price" :
1.29, "countryOfOrigin" : "USA" }
Apples
[
{ "type": "granny smith", "price": 2.99, "countryOfOrigin": "USA" },
{ "type": "golden delicious", "price": 0.99, "countryOfOrigin":
"Ireland" },
{ "type": "gala", "price": 1.29, "countryOfOrigin": "USA" },
{ "type": "empire", "price": 1.59, "countryOfOrigin": "USA" },
{ "type": "delicious", "price": 1.59, "countryOfOrigin": "USA" },
{ "type": "macintosh", "price": 0.99, "countryOfOrigin": "USA" },
{ "type": "fuji", "price": 0.99, "countryOfOrigin": "Chile" },
{ "type": "golden delicious", "price": 0.99, "countryOfOrigin":
"Mexico" },
{ "type": "crab", "price": 0.09, "countryOfOrigin": "Canada"
}
]
Oranges
[
{ "type": "navel", "price": 2.99, "countryOfOrigin": "USA" },
{ "type": "seville", "price": 0.99, "countryOfOrigin": "Spain" },
{ "type": "blood", "price": 1.69, "countryOfOrigin": "USA" },
{ "type": "mandarin", "price": 1.59, "countryOfOrigin": "USA" },
{ "type": "jaffa", "price": 1.59, "countryOfOrigin": "Israel" },
{ "type": "lima", "price": 0.99, "countryOfOrigin": "Brazil" },
{ "type": "cara cara", "price": 0.99, "countryOfOrigin": "Venezuela" },
{ "type": "cara cara", "price": 1.29, "countryOfOrigin": "USA" },
{ "type": "cherry", "price": 1.09, "countryOfOrigin": "Japan" },
{ "type": "queen", "price": 1.09, "countryOfOrigin": "South Africa" }
]
Countries
[
{ "country": "USA", "continent": "North America" },
{ "country": "Spain", "continent": "Europe" },
{ "country": "Brazil", "continent": "South America" },
{ "country": "Venezuela", "continent": "South America" },
{ "country": "Japan", "continent": "Asia" },
{ "country": "South Africa", "continent": "Africa" },
{ "country": "Chile", "continent": "South America" },
{ "country": "Ireland", "continent": "Europe" },
{ "country": "Mexico", "continent": "North America" },
{ "country": "Canada", "continent": "North America" },
{ "country": "China", "continent": "Asia" }
]