About
MongoDB is a NoSQL, document-centric database for building highly available and scalable web applications. MongoDB makes it easy for developers to store, manage, and retrieve data when creating applications.
The MongoDB cheat sheet covers basic commands and tasks for using MongoDB. It introduces key concepts, like collections and indexes, and explains how to perform common tasks, including setting query results to a varable and using MongoDB’s aggregate method. You'll also find tips on how to carefully execute dangerous tasks, like dropping collections from a database.
Download the MongoDB cheat sheet and learn how to:
- Access the Mongo shell
- Navigate around Mongo
- Create, delete, and list users in a database
- Perform basic queries against a collection
- Add, update, and remove documents
- Use a variable to store query results
- Work with indexes
- Use aggregations in MongoDB
With Red Hat Developer cheat sheets, you get essential information right at your fingertips so you can work faster and smarter. Easily learn new technologies and coding concepts and quickly find the answers you need.
Excerpt
Working with a collection
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 all collections
show collections
Example:
> show collections
apples
oranges
pears
Delete a collection
db.<collection_name>.drop()
Example:
> db.pears.drop()
True
Working with documents
The following sections show you how perform basic queries against a given collection in a database.
Show all documents in a collection
db.<collection_name>.find()
db.["<collection_name>"].find()
Example:
> db["apples"].find()
"_id" : ObjectId("627d9053f7e6008a00844a81"), "type" : "granny smith",
"price" : 2.99, "countryOfOrigin" : "USA" }
{ "_id" : ObjectId("627d9053f7e6008a00844a82"), "type" : "golden
delicious", "price" : 0.99, "countryOfOrigin" : "Ireland" }
{ "_id" : ObjectId("627d9053f7e6008a00844a83"), "type" : "gala", "price" :
1.29, "countryOfOrigin" : "USA" }
{ "_id" : ObjectId("627d9053f7e6008a00844a84"), "type" : "empire",
"price" : 1.59, "countryOfOrigin" : "USA" }
{ "_id" : ObjectId("627d9053f7e6008a00844a85"), "type" : "delicious",
"price" : 1.59, "countryOfOrigin" : "USA" }
{ "_id" : ObjectId("627d9053f7e6008a00844a86"), "type" : "macintosh",
"price" : 0.99, "countryOfOrigin" : "USA" }
{ "_id" : ObjectId("627d9053f7e6008a00844a87"), "type" : "fuji", "price" :
0.99, "countryOfOrigin" : "Chile" }
{ "_id" : ObjectId("627d9053f7e6008a00844a88"), "type" : "golden
delicious", "price" : 0.99, "countryOfOrigin" : "Mexico" }
{ "_id" : ObjectId("627d9053f7e6008a00844a89"), "type" : "crab", "price" :
0.09, "countryOfOrigin" : "Canada" }