Getting Started with MongoDB

After MongoDB is installed, you can start MongoDB client with command.

mongo

List All Databases

To see list of all available database, use

show dbs

Create A Database

To create a database, run

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

show collections

Creating Tables

In MongoDB, tables are called Collections. To create a collection, use

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

db.COLLECTION_NAME.insert(JSON_DATA)

Example

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

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

db.servers.find({ram: "64G"})

MongoDB

Need help with Linux Server or WordPress? We can help!

Leave a Reply

Your email address will not be published. Required fields are marked *