Do more with Mongo shell

6:25 AM Shashank Tiwary 0 Comments


Mongo ( mongo.exe )


Mongo is a client program use to execute query and command against a mongodb server. This program ships with Mongodb package.
I don't like to work with command line tools (specially windows based) but in case of mongo its really fun. Mongo provides us a javascript interpreted shell and developer who loves javascript is also felt in love with mongo shell.
To  demonstrate some features of mongo shell lets open your mongo client shell and connect with your mongod instance.

Insert a document in product collection and then update it using help of javascript object.

 

Below is the commands that I used. Do copy paste to save your time
> db.product.insert({ "_id" : "ac3", "name" : "AC3 Phone", "brand" : "ACME", "type" : "phone", "price" : 200, "warranty_years" : 1, "available" : true })

Now to update the inserted document we can use a javascript  object like below.
> p = db.product.findOne({"_id":"ac3"}) // set to find document
> p.price = 199  // update price field
> p.warranty_years = 2
> db.product.save(p) // update product into database ... easy hum.
The above object p only exist for the current mongo shell session.

Writing multiline script in shell

 

Mongo shell support line continuation and it does this intelligently. If you end a line with an open parenthesis ('('), an open brace ('{'), or an open bracket ('['), then the subsequent lines start with ellipsis ("...") until you enter the corresponding closing parenthesis (')'), the closing brace ('}') or the closing bracket (']'). To end continuation mode press enter/return key twice.
> db.product.update({ "_id" : "ac3"},
... { "_id" : "ac3", "name" : "AC3 Phone", "brand" : "ACME", "type" : "phone",
... "price" : 200, "warranty_years" : 1, "available" : true })
Once you complete the expression the mongo shell execute your query.

See method implementation details to know more

 

In mongo shell to print value of an object to the console you just need to specify the object name and press enter. As because in javascript a function is an object you can also see its value i.e.; it definition in similar fashion. Its some time helpful when you want to know the actual command applied by the method in mongo shell. Lets see a example below.
> db.getCollectionNames  // use to get collection names present in current database

function (){
    var all = [];

    var nsLength = this._name.length + 1;

    var c = this.getCollection( "system.namespaces" ).find();
    while ( c.hasNext() ){
        var name = c.next().name;

        if ( name.indexOf( "$" ) >= 0 && name.indexOf( ".oplog.$" ) < 0 )
            continue;

        all.push( name.substring( nsLength ) );
    }

    return all.sort();
}

You can see above this method uses system.namespaces' collection to get details about collection names present in database. Cool isn't it.

Running javascript file with mongo shell

 

To run your own javascript files with mongo shell you can use command like below
mongo <databasename> <your_js_file>

You can also save resulting execution output  by mongo shell in file. Lets see the command below;
mongo <databasename> <your_js_file> >> <result_file>

Note : The mongo shell, by default, doesn't print out anything when running a script file.  This behavior is different than when run interactively.
To print out to the file in non-interactive mode use printjson like this
printjson( db.product.find());
For more difference between interactive and non interactive execution environment go here

Conclusion

 

I would like to say that its about the right decision made by mongodb team to use javascript interpreter for command line tool.
There are many more feature I will discuss with you later. Please comment to enhance my blog.

0 comments: