Install MongoDB

Installing MongoDB in your system:

  • Go to MongoDB site and download the MongoDB package for your OS and extract it in your local system
  • you will see a bin folder and inside bin lot of binaries. you will see binary called mongod and that is the actual daemon runs MongoDB
  • mongo binary gives you a client to talk to your database

Start MongoDB:

  • Go to mongod binary and then type mongod
  • mongod will lookfor the default data directory /data/db inside root directory and if you don’t have the directory then it will fail
  • so you can create a custom data directory with mongod
    • mongod –dbpath “custom_directory path”
  • It will start the MongoDB immediately and connect to db called test
  • the last line will show you the port number where the mongodb runs
  • you can use command db to see the current database
  • if you want to connect to a different database then write use <dbname>. ex: use techkatak
  • you can see all databases by command show dbs

Connect to a database and Query the Database:

>show dbs : list all dbs available in MongoDB

>use <db_name>: connect to a perticular database

>show collections: list all the collections for that database

>db.<collection_name>.find() : select records from collection

>db.<collection_name>.find().pretty(): to make the selection readable

>db.<collection_name>.find((<column_name> : <condition>)): this is similar to the where clause in RDBMS. it would filter the selection based on condition

>db.<collection_name>.findone(): it would give you one record similar to rownum=1 in RDBMS

 >>db.<collection_name>.insert(<a>):Insert JSON document to collection where as <a> is a JSON object

>db.<collection_name>.remove(): Delete all records from collection, you can use where clause to delete selective records

>db.<collection_name>.count(): count records in a collection

© 2015, www.techkatak.com. All rights reserved.