Wednesday, October 25, 2017

Learning MongoDB command on Lubuntu

Learn MongoDB command on Lubuntu

If you haven't install MongoDB yet, please see my previous article on how to install MongoDB on Lubuntu 16.04. In this article i will give you some guides on basic MongoDB commands, hopefully this tutorial could help someone who learn MongoDB for the first time.

Using MongoDB shell

MongoDB shell is where you can run MongoDB commands, to open MongoDB shell simply type in 'mongo' on the command line/terminal

Showing list of databases

Once you are on MongoDB shell, you can show list of database using 'dbs' command
show dbs

Create and use database

To create new database, you can run 'use' command followed by the name of the database you wish to create. The same command also used to switch from one database to another, basically if the database is not exist it will create new one, if exist it will switch to that database.
use [database-name]
use mydatabase
use sales
use whatever

Show list of collections

Collection in MongoDB is like table on relational database (like MySQL), in MongoDB you can show list of collections with this:
show collections

Create new collection

To create new collection in MongoDB, you can run db.createCollection() and give a string as parameter for the name of the collection.

Insert data on MongoDB

To insert data to collection in MongoDB, you can use insert() method, of course you need to specify the which collection you wish to insert the data. Note that the data should be in JSON format.
Example:{"car_name":"Mazda RX 7","color":"red","year":"2005"})

Show list of data on MongoDB

To show list of data inside a collection, you can run find() command without any parameter.

Searching specific data on MongoDB

You can also search for specific data or field, the find() method can take parameter for showing specific data, here's an example:

Update data on MongoDB

To update data on MongoDB, you can use the update method, same as insert and find, you need to specify which collection to update and the filter such as _id or other field.{_id:ObjectId("id-of-the-record")}, {$set:{field_name:"value"}})
Example:{_id:ObjectId("59f04d6c91c36df211b24f7c")}, {$set:{color:"blue"}}){_id:ObjectId("59f04d6c91c36df211b24f7c")}, {$set:{color:"blue",year:"2017"}}){car_name:"BMW M3"}, {$set:{color:"blue",year:"2017"}})

Delete data on MongoDB

To delete a data on MongoDB, you can use remove() method with parameter the _id of the record you wish to delete.{_id:ObjectId("id-of-the-record")})

Those are some basic MongoDB command that you can try, for more detail you can visit MongoDB documentation/manual

No comments:

Post a Comment