Getting Started with MongoDB
After MongoDB is installed, you can start MongoDB client with command.
1 |
mongo |
List All Databases
To see list of all available database, use
1 |
show dbs |
Create A Database
To create a database, run
1 |
use DB_NAME |
This will create a new database if not present and switch to it.
See all Collections
Once you switched to a database using “use DB_NAME” command, you can see collections (or tables) in a database with command
1 |
show collections |
Creating Tables
In MongoDB, tables are called Collections. To create a collection, use
1 |
db.createCollection("COLLECTION_NAME") |
Here i create a collection with name “servers”.
Inserting Data into a Collection
You can insert data into a collection in Jason format. To insert use following format
1 |
db.COLLECTION_NAME.insert(JSON_DATA) |
Example
1 |
db.servers.insert({hostname: "server22.hosthat.com", ip: "144.217.71.213", os: "CloudLinux 7.4", ram: "64G", cpu: "Intel(R) Xeon(R) CPU D-1521 @ 2.40GHz"}) |
When you insert data MongoDB will auto create a unique “_id” field.
Listing Data in Collection
To list all available data in a collection, use
1 |
db.COLLECTION_NAME.find() |
This will list all data. To list specific data, you can pass JSON string to find(), for example, to find all servers to 64G RAM, use
1 |
db.servers.find({ram: "64G"}) |