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:

Up and running Mongodb with C#

1:23 AM Shashank Tiwary 0 Comments

Following is the step for up and running Mongodb with C#

Download the Mongodb package from here

Mongodb package come with binary executable and msi (Microsoft Installer) in 32bit and 64bit version. I would prefer to use 64bit msi version if your OS is capable of.Here is the url to download from.

Running mongod instance server

After installing your package to run mongodb instance server open a command prompt window and execute command mongod -dbpath="<your database storage path>". To test every thing is OK run a mongo client executable from command prompt to connect with running server. Use this command below like that mongo. mongo client automatically connect to the localhost server with default port 27017.  To know more about the mongod and mongo command use -help argument.
Here is the output generated by mongod command on my machine


And output generated by mongo client


After executing mongod command it create some files and allocate few space on disk for data storage. Open a visual studio editor and create a new console project. To install mongodb official drivers using nuget package manager console and type the following command into the console PM> Install-Package mongocsharpdriver It will install the most recent driver for you. If you are interested in particular version of driver use -version command argument to specify in nuget command.

Lets write the first code to connect to our mongodb server

namespace MongoFirst
{
    using MongoDB.Bson;
    using MongoDB.Driver;
    using System;

    public class Program
    {
        static void Main(string[] args)
        {
            // create a client object
            MongoClient client = new MongoClient("mongodb://localhost:27017/"); // mongodb connection string
            // create a server object
            MongoServer server = client.GetServer();
            // create a database object with database name "test"
            MongoDatabase db = server.GetDatabase("test");
            // get collection object cars from test database
            MongoCollection cars = db.GetCollection("cars");
            // insert documents
            cars.Save(new Cars { Name = "Mongodb" });
            cars.Save(new Cars { Name = "Oracle" });

            // loop throug each item in cars collection
            foreach (var car in cars.FindAllAs())
            {
                Console.WriteLine("Database : {0}", car.Name);
            }

            Console.ReadKey();
        }
    }

    public class Cars
    {
        // a collection always have a field '_id' in mongodb, 
        // you can also use different type rather that ObjectId here
        public ObjectId Id { get; set; } 
        public string Name { get; set; }
    }
}
You can also specify mongodb database name in connection string. For more details about the mongodb connection string visit here

0 comments: