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. |
Tag: MongoDB Cheat Sheet
MongoDB is a cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas. MongoDB Cheat Sheet tries to provide a basic reference for beginner and advanced developers, lower the entry barrier for newcomers, and help veterans refresh the old tricks.
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) . |
Keystroke | Function |
---|---|
Up-arrow | previous-history |
Down-arrow | next-history |
Home | beginning-of-line |
End | end-of-line |
Tab | autocomplete |
Left-arrow | backward-character |
Right-arrow | forward-character |
Ctrl-left-arrow | backward-word |
Ctrl-right-arrow | forward-word |
Meta-left-arrow | backward-word |
Meta-right-arrow | forward-word |
Ctrl-A | beginning-of-line |
Ctrl-B | backward-char |
Ctrl-C | exit-shell |
Ctrl-D | delete-char (or exit shell) |
Ctrl-E | end-of-line |
Ctrl-F | forward-char |
Ctrl-G | abort |
Ctrl-J | accept-line |
Ctrl-K | kill-line |
Ctrl-L | clear-screen |
Ctrl-M | accept-line |
Ctrl-N | next-history |
Ctrl-P | previous-history |
Ctrl-R | reverse-search-history |
Ctrl-S | forward-search-history |
Ctrl-T | transpose-chars |
Ctrl-U | unix-line-discard |
Ctrl-W | unix-word-rubout |
Ctrl-Y | yank |
Ctrl-Z | Suspend (job control works in linux) |
Ctrl-H (i.e. Backspace) | backward-delete-char |
Ctrl-I (i.e. Tab) | complete |
Meta-B | backward-word |
Meta-C | capitalize-word |
Meta-D | kill-word |
Meta-F | forward-word |
Meta-L | downcase-word |
Meta-U | upcase-word |
Meta-Y | yank-pop |
Meta-[Backspace] | backward-kill-word |
Meta-< | beginning-of-history |
Meta-> | end-of-history |
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