https://github.com/cheatsheet-lang/mongodb
Cheatsheet for MongoDB
https://github.com/cheatsheet-lang/mongodb
cheatsheet database drop hacktoberfest hacktoberfest2020 mongodb mongotop nosql pipeline retrieve-data schema-less stage syntax
Last synced: about 1 year ago
JSON representation
Cheatsheet for MongoDB
- Host: GitHub
- URL: https://github.com/cheatsheet-lang/mongodb
- Owner: Cheatsheet-lang
- License: mit
- Created: 2019-12-13T02:11:10.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2021-10-08T05:45:11.000Z (over 4 years ago)
- Last Synced: 2025-04-19T11:09:09.673Z (about 1 year ago)
- Topics: cheatsheet, database, drop, hacktoberfest, hacktoberfest2020, mongodb, mongotop, nosql, pipeline, retrieve-data, schema-less, stage, syntax
- Homepage:
- Size: 18.6 KB
- Stars: 8
- Watchers: 0
- Forks: 4
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# MongoDB Cheatsheet
### General Commands
#### Opens the monogDB shell
```mongo
$ mongo
```
## Commands
### Basics
#### Create and Use Database
```mongo
use ;
```
#### See Default database
```mongo
db;
```
#### Create Collection
```mongo
db.createCollection("");
```
#### Inserting One Document
```mongo
db..insert({name: "Bob", age: 20, desg: "Analytics"}); // Inserting One Document
```
#### Inserting Many Documents
```mongo
db..insertMany([{name: "Alice", age: 30, desg: "Devops"}, {name: "Sue", age: 35, desg: "Full stack"}]);
```
#### Display all Documents
```mongo
db..find();
```
#### Display Documents in JSON Format
```mongo
db..find().pretty();
```
#### Display Distinct
```mongo
db..distinct("name");
```
#### Update Collection
```mongo
db..update({ refKey : "refValue" }, { $set : { changeKey : "changeValue"}})
```
`refKey` and `refValue` refers to the key and value pair from the document which needs to be updated.
`changeKey` and `changeValue` refers to the actual content which needs to be updated.
#### Drop Collection
```mongo
db..drop();
```
### Operations
#### Projection
When we want to retrieve only specific number of fields from a set of documents, this method is used.
The fields(keys) we wish to retrieve are passed in find method with true Boolean condition.
If we don’t want to retrieve _id we can hide it by giving false Boolean value to it.
```
db..find({}, key:1, _id:0)
```
#### Limit
If we want to retrieve first specific number of document from a collection this method is used.
The number of elements we wish to retrieve is passed in the limit method.
```
db..find({}, key:1, _id:0).limit(number)
```
#### Skip
Imagine skipping a particular number of documents from a collection while retrieving data.
In such cases, skip method is useful.
```
Query: db..find({}, key:1, _id:0).skip(number)
```
#### Sort
As the name suggests this method is useful when we wish to retrieve data in a particular manner.
If we want to retrieve data an ascending order, 1 is passed or -1 if descending order.
```
db..find().sort(refKey:num)
```
### Projection Methods
#### Aggregation :
Aggregations operations process data records and return computed results.
Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result.
For the aggregation in MongoDB, you should use `aggregate()` method.
```
db..aggregate(Aggregate_operation)
```
#### `$project` method :
Passes along the documents with only the specified fields to the next stage in the pipeline. This may be the existing fields from the input documents or newly computed fields.
```
{ “$project”: { } }
```
#### `$match` method :
Filters the documents to pass only the documents that match the specified condition(s) to the next pipeline stage.
```
{ “$match” : { } }
```
#### `$group` method :
$group is used to group the documents by some specified expression.
```
{ $group: { _id: , : { : } } }
```
### Indexing
An index in MongoDB is a special data structure that holds the data of few fields of documents on which the index is created.
#### Apply a new indexing
```
db.collection_name.createIndex({key: 1 or -1})
```
Here, '1' represents ascending order of indexing whereas '-1' descending.
#### Retrieve the index
```
db..getIndexes()
```
#### Drop the existing index
```
db..dropIndexes()
```
### Replication
Replication is the process of synchronizing data across multiple servers. Replication provides redundancy and increases data availability with multiple copies of data on different database servers.
#### Set Up a Replica Set
```
mongod --port "PORT" --dbpath "YOUR_DB_DATA_PATH" --replSet "REPLICA_SET_INSTANCE_NAME"
```
#### Add Members to Replica Set
```
>rs.add(HOST_NAME:PORT)
### Sharding
Sharding is the process of storing data records across multiple machines and it is MongoDB's approach to meeting the demands of data growth.
### Create Backup
#### Dump MongoDB Data
```
>mongodump
```
#### Restore data
```
>mongorestore
```
### Deployment
#### When you are preparing a MongoDB deployment, you should try to understand how your application is going to hold up in production.
```
mongostat
```
#### This command checks the status of all running mongod instances and return counters of database operations.
#### To run the command, start your mongod instance. In another command prompt, go to bin directory of your mongodb installation and type mongostat.
```
D:\set up\mongodb\bin>mongostat
```
```
mongotop
```
#### This command tracks and reports the read and write activity of MongoDB instance on a collection basis. By default, mongotop returns information in each second, which you can change it accordingly.
#### To run the command, start your mongod instance. In another command prompt, go to bin directory of your mongodb installation and type mongotop.
```
D:\set up\mongodb\bin>mongotop
```
#### To change mongotop command to return information less frequently, specify a specific number after the mongotop command.
```mongo
D:\set up\mongodb\bin>mongotop 30
```
#### The above example will return values every 30 seconds.
### Running the commands
To run a command against the current database, use
```mongo
db.runCommand( { } )
```
To run an administrative command against the admin database, use
```mongo
db.adminCommand( { } )
```