MongoDB: Shell JavaScript Operations Cheat Sheet

db.auth()If running in secure mode, authenticate the user.
coll = db.<collection>Set a specific collection in the current database to a variable coll, as in the following example:copycopiedcoll = db.myCollection; You can perform operations on the myCollection using the variable, as in the following example:copycopiedcoll.find();
db.collection.find()Find all documents in the collection and returns a cursor.See the db.collection.find() and Query Documents for more information and examples.See Iterate a Cursor in the mongo Shell for information on cursor handling in the mongo shell.
db.collection.insertOne()Insert a new document into the collection.
db.collection.insertMany()Insert multiple new documents into the collection.
db.collection.updateOne()Update a single existing document in the collection.
db.collection.updateMany()Update multiple existing documents in the collection.
db.collection.save()Insert either a new document or update an existing document in the collection.
db.collection.deleteOne()Delete a single document from the collection.
db.collection.deleteMany()Delete documents from the collection.
db.collection.drop()Drops or removes completely the collection.
db.collection.createIndex()Create a new index on the collection if the index does not exist; otherwise, the operation has no effect.
db.getSiblingDB()Return a reference to another database using this same connection without explicitly switching the current database. This allows for cross database queries.

MongoDB: Queries Cheat Sheet

db.collection.find(<query>)Find the documents matching the <query> criteria in the collection. If the <query> criteria is not specified or is empty (i.e {} ), the read operation selects all documents in the collection.The following example selects the documents in the users collection with the name field equal to "Joe":copycopiedcoll = db.users; coll.find( { name: “Joe” } ); For more information on specifying the <query> criteria, see Specify Equality Condition.
db.collection.find(<query>, <projection>)Find documents matching the <query> criteria and return just specific fields in the <projection>.The following example selects all documents from the collection but returns only the name field and the _id field. The _id is always returned unless explicitly specified to not return.copycopiedcoll = db.users; coll.find( { }, { name: true } ); For more information on specifying the <projection>, see Project Fields to Return from Query.
db.collection.find().sort(<sort order>)Return results in the specified <sort order>.The following example selects all documents from the collection and returns the results sorted by the name field in ascending order (1). Use -1 for descending order:copycopiedcoll = db.users; coll.find().sort( { name: 1 } );
db.collection.find(<query>).sort(<sort order>)Return the documents matching the <query> criteria in the specified <sort order>.
db.collection.find( ... ).limit( <n> )Limit result to <n> rows. Highly recommended if you need only a certain number of rows for best performance.
db.collection.find( ... ).skip( <n> )Skip <n> results.
db.collection.count()Returns total number of documents in the collection.
db.collection.find(<query>).count()Returns the total number of documents that match the query.The count() ignores limit() and skip(). For example, if 100 records match but the limit is 10, count() will return 100. This will be faster than iterating yourself, but still take time.
db.collection.findOne(<query>)Find and return a single document. Returns null if not found.The following example selects a single document in the users collection with the name field matches to "Joe":copycopiedcoll = db.users; coll.findOne( { name: “Joe” } ); Internally, the findOne() method is the find() method with a limit(1).

MongoDB Keyboard Shortcuts

KeystrokeFunction
Up-arrowprevious-history
Down-arrownext-history
Homebeginning-of-line
Endend-of-line
Tabautocomplete
Left-arrowbackward-character
Right-arrowforward-character
Ctrl-left-arrowbackward-word
Ctrl-right-arrowforward-word
Meta-left-arrowbackward-word
Meta-right-arrowforward-word
Ctrl-Abeginning-of-line
Ctrl-Bbackward-char
Ctrl-Cexit-shell
Ctrl-Ddelete-char (or exit shell)
Ctrl-Eend-of-line
Ctrl-Fforward-char
Ctrl-Gabort
Ctrl-Jaccept-line
Ctrl-Kkill-line
Ctrl-Lclear-screen
Ctrl-Maccept-line
Ctrl-Nnext-history
Ctrl-Pprevious-history
Ctrl-Rreverse-search-history
Ctrl-Sforward-search-history
Ctrl-Ttranspose-chars
Ctrl-Uunix-line-discard
Ctrl-Wunix-word-rubout
Ctrl-Yyank
Ctrl-ZSuspend (job control works in linux)
Ctrl-H (i.e. Backspace)backward-delete-char
Ctrl-I (i.e. Tab)complete
Meta-Bbackward-word
Meta-Ccapitalize-word
Meta-Dkill-word
Meta-Fforward-word
Meta-Ldowncase-word
Meta-Uupcase-word
Meta-Yyank-pop
Meta-[Backspace]backward-kill-word
Meta-<beginning-of-history
Meta->end-of-history

MongoDB: Commands Cheat Sheet

Start and stop the MongoDB Database:

sudo service mongod start
sudo service mongod stop

Access the MongoDB database using Shell:

mongo --host localhost:27017

Show all databases:

show dbs

Create a database, say, testdb; Switch to the database:

use testdb

Until a collection is created in a database, the database name is not listed as a result of execution of the command, “show dbs.”

Add a collection:

db.createCollection("user")

Show all collections in a database; Execute the “use dbname” command to access the database before executing the command given below.

show collections
show tables

The following command also work:

db.getCollectionNames()

Insert a record in the collection; A record is inserted in the collection, “user.”

db.user.insert({"name": "Ajitesh Shukla", "location": "hyderabad", "username": "eajitesh"})

Display list of records of a collection; “user” collection is used.

db.user.find()
db.user.find().pretty()

Display a list of records matching with value (s) of specific fields:

db.user.find({"username": "eajitesh"})
db.user.find({"username": "eajitesh", "location": "hyderabad"})

Drop the collection:

db.user.drop()

Create users in the database; The below command creates a user with username as “ajitesh” and having the role such as “readWrite” and “dbAdmin”

db.createUser({"user": "ajitesh", "pwd": "gurukul", "roles": ["readWrite", "dbAdmin"]})

Show users; If executed without selecting a database, it displays all users along with database information.

show users

Login into the database with username and password:

mongo -u USERNAME -p PASSWORD --authenticationDatabase DATABASENAME

For user created in above command, the login command would look like the following:

mongo -u ajitesh -p gurukul --authenticationDatabase testdb