The mongo shell is an interactive JavaScript shell for MongoDB, and is part of all MongoDB distributions.To start shell goto bin directory as showed in previous post

$ cd mongo-directory/bin/
$ ./mongod

Open new tab and type 

$ ./mongo

Insert and Find Data :-

Once prompt open ( “>”) after running ./mongo, now we are ready to add data in it. In order to add data we  have to create table or have to choose existing table. In order to do this use

> show db ( To show existing databases )
> use <database_name> ( To create new database, if it not exist )

For instance let’s choose one database say “demo”. In order to insert things in demo database we use insert key for eg:

>use demo
>db.things.insert ({"a" : 1, "b" : 2, "c" : 3 })  [Here things represent collections]

To see what and how data is stored we use find() keyword for eg:

>db.things.find()
 Output :
 { "_id" : ObjectId("5446bfe646e4915b9e33dfb2"), "a" : 1, "b" : 2, "c" : 3 }

Similarly we can add more things in it like :

>db.things.insert ({"d" : 4, "e" : 5 })
>db.things.find()
 Output
 { "_id" : ObjectId("5446bfe646e4915b9e33dfb2"), "a" : 1, "b" : 2, "c" : 3 }
 { "_id" : ObjectId("5446bff646e4915b9e33dfb3"), "d" : 4, "e" : 5 }

As we are in totally javascript environment so we can use for loops and other javascript stuff in it. For eg: if we want to add 10 entries in x using for loop we can add it by this :

>for (i=0; i<10; i++) {db.things.insert ({ "x" : i})}
 Output
 { "_id" : ObjectId("5446c06a46e4915b9e33dfb4"), "x" : 0 }
 { "_id" : ObjectId("5446c06a46e4915b9e33dfb5"), "x" : 1 }
 { "_id" : ObjectId("5446c06a46e4915b9e33dfb6"), "x" : 2 }
 { "_id" : ObjectId("5446c06a46e4915b9e33dfb7"), "x" : 3 }
 { "_id" : ObjectId("5446c06a46e4915b9e33dfb8"), "x" : 4 }
 { "_id" : ObjectId("5446c06a46e4915b9e33dfb9"), "x" : 5 }
 { "_id" : ObjectId("5446c06a46e4915b9e33dfba"), "x" : 6 }
 { "_id" : ObjectId("5446c06a46e4915b9e33dfbb"), "x" : 7 }
 { "_id" : ObjectId("5446c06a46e4915b9e33dfbc"), "x" : 8 }
 { "_id" : ObjectId("5446c06a46e4915b9e33dfbd"), "x" : 9 }
Advertisements