Tuesday, 20 January 2015

Basic Commands

Now that u have a running Mongodb, i will start off with some very basic commands
If u haven't installed it yet, see the steps here

1. db;
this shows the database currently selected. since we haven't created any db it returns test, which is present by default.

2. show dbs or show databases;
This shows the list of all db's present in your system.

3. use dbname;
In Mongodb, there is no need to create a db before using it.By using this command mongo searches for the db. If the db is not found, it creates one and switches to that db.

4. db.dropDatabase():
Drops the database currently selected.

5. show collections;
This shows all the collections present in the db.

6. db.collectionname.insert():
If the collection name is not found,it creates a collection, else it inserts into the collection.
We pass the JSON document as the argument for the insert function.

example:
db.test1.insert({"name":"ravi","country":"India"});
db.test1.insert({"name":"saketh","interests":["chess","coding"]});
we can also insert documents inside a document like
db.test1.insert({name:"harry",age:17,address:[{school:"hogwarts"},{home:"godricks hollow"}]}); 
7. db.collectionname.find():
This shows all the documents inside a collection.

example: db.test1.find()

{ "_id" : ObjectId("54bf453f22fc6eaa4507787a"), "name" : "ravi","country":"India" }
{ "_id" : ObjectId("54bf48b022fc6eaa4507787b"), "name" : "saketh", "interests" : [ "chess", "coding" ] }
{ "_id" : ObjectId("54bf4d4e22fc6eaa4507787c"), "name" : "harry", "age" : 17, "address" : [ { "school" : "hogwarts" }, { "home" : "godricks hollow" } ] }

if we add pretty() command at the end of the find(), the shell shows the data in proper hierarchical manner, like

db.test1.find().pretty()

{
        "_id" : ObjectId("54bf453f22fc6eaa4507787a"),
        "name" : "ravi",
        "country":"India"
}
{
        "_id" : ObjectId("54bf48b022fc6eaa4507787b"),
        "name" : "saketh",
        "interests" : [
                "chess",
                "coding"
        ]
}
{
        "_id" : ObjectId("54bf4d4e22fc6eaa4507787c"),
        "name" : "harry",
        "age" : 17,
        "address" : [
                {
                        "school" : "hogwarts"
                },
                {
                        "home" : "godricks hollow"
                }
        ]
}








No comments:

Post a Comment