MongoDB Quick Reference Cheatsheet





- Connect to MongoDB Server: `mongo` or 'mongosh'
- Stop MongoDB Server: `use admin; db.shutdownServer();`

#### Basic Commands
- Show Databases: `show dbs`
- Use a Database: `use <database_name>`
- Show Collections: `show collections`
- Create a Collection: `db.createCollection("<collection_name>")`
- Drop a Database: `db.dropDatabase()`
- Drop a Collection: `db.<collection_name>.drop()`

#### CRUD Operations

##### Create
- Insert a Document: `db.<collection_name>.insert({field1: value1, field2: value2})`
- Insert Multiple Documents: `db.<collection_name>.insertMany([{doc1}, {doc2}, ...])`

##### Read
- Find Documents: `db.<collection_name>.find({field: value})`
- Find One Document: `db.<collection_name>.findOne({field: value})`


##### Update
- Update a Document: `db.<collection_name>.update({field: value}, {$set: {field_to_update: new_value}})`
- Update Multiple Documents: `db.<collection_name>.update({field: value}, {$set: {field_to_update: new_value}}, {multi: true})`

##### Delete
- Delete a Document: `db.<collection_name>.remove({field: value})`
- Delete Multiple Documents: `db.<collection_name>.remove({field: value}, {justOne: false})`


#### Query Operators
- Equality: `{field: value}`
- Greater Than: `{field: {$gt: value}}`
- Less Than: `{field: {$lt: value}}`
- In Array: `{field: {$in: [value1, value2]}}`
- Logical AND: `$and: [{cond1}, {cond2}]`
- Logical OR: `$or: [{cond1}, {cond2}]`

#### Indexing
- Create an Index: `db.<collection_name>.createIndex({field: 1})`
- List All Indexes: `db.<collection_name>.getIndexes()`
- Drop an Index: `db.<collection_name>.dropIndex("index_name")`

#### Aggregation
- Aggregate Data: `db.<collection_name>.aggregate([{$group: {_id: "$field", total: {$sum: 1}}}])`

#### Authentication
- Create a User: `db.createUser({user: "username", pwd: "password", roles: ["readWrite"]})`
- Authenticate: `db.auth("username", "password")`
- List Users: `db.getUsers()`


#### Backup and Restore
- Backup: `mongodump --db <database_name> --out <backup_directory>`
- Restore: `mongorestore --db <database_name> <backup_directory>`

#### Miscellaneous
- Show Server Status: `db.serverStatus()`
- Show Current Database: `db.getName()`
- Exit MongoDB Shell: `quit()`

Remember to replace `<database_name>`, `<collection_name>`, `<field>`, `<value>`, and other placeholders with your specific values. This cheatsheet covers some of the most commonly used MongoDB commands and operations, but MongoDB is a versatile NoSQL database, and there are many more features and commands to explore in the documentation.