Sunday, June 1, 2014

MongoDB Qucik Start Part One

MongoDB (from "humongous") is an open-source document database, and the leading NoSQL database. Written in C++, MongoDB features:
  • Document-Oriented Storage
  • Full Index Support
  • Replication & High Availability
  • Auto-Sharding
  • Querying
  • Fast In-Place Updates
  • Map/Reduce
  • GridFS
  • MongoDB Management Service
  • Partner with MongoDB
Now most of PAAS support MongoDB as their run time enviorment,it is possible for us to learn this language.MongoDB provide 32bit and 64bit binary package,you can download it from
After you downloaded the package and unzip it to your hard disk.Here I unzip to d:/mongodb.Now we create another folder to keep the db data.

In order to start the MongoDB ,you must run the mongod.exe in the bin folder.

Run MongoDB  as service 

mongod --bind_ip yourIPadress --logpath "C:\data\dbConf\mongodb.log" --logappend --dbpath "C:\data\db" --port yourPortNumber --serviceName "YourServiceName" --serviceDisplayName "YourServiceName" --install

--bind_ipbind IP,if bind,only for local visit 
--logpathspecified MongoDB log file 
--logappenduse append way to write the log
--dbpathspecified the db path
--portspecified port,default 27017
--serviceNamespecified service name
--installspecify as windowns service

 MongoDB shell
After start the MongoDB,you can use shell script to do some operaions.

a) default connect
b) insert sample record
c)show all dbs

d) switch to use another db

e)Define document

> document=({"user_id" : "ABCDBWN","password" :"ABCDBWN" ,"date_of_join" :
"15/10/2010" ,"education" :"B.C.A." , "profession" : "DEVELOPER","interest" :
"MUSIC","community_name" :["MODERN MUSIC", "CLASSICAL
MUSIC","WESTERN MUSIC"],"community_moder_id" : ["MR. BBB","MR. JJJ","MR
MMM"],"community_members" : [500,200,1500],"friends_id" :
["MMM123","NNN123","OOO123"],"ban_friends_id" :
You can see the below document structure.

f)insert document


g)Check db collection records

MongoDB with the Java API

You must download the MongoDB driver from below address

Sample code fro

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;

import java.util.List;
import java.util.Set;

 * The tutorial from
public class QuickTour {
     * Run this main method to see the output of this quick example.
     * @param args takes no args
     * @throws UnknownHostException if it cannot connect to a MongoDB instance at localhost:27017
    public static void main(final String[] args) throws UnknownHostException {
        // connect to the local database server
        MongoClient mongoClient = new MongoClient();
        for (String s : mongoClient.getDatabaseNames()) {
            System.out.println("Database name is:"+s);

        // get handle to "mydb"
        DB db = mongoClient.getDB("test");

        // Authenticate - optional
        // boolean auth = db.authenticate("foo", "bar");

        // get a list of the collections in this database and print them out
        Set<String> collectionNames = db.getCollectionNames();
        for (final String s : collectionNames) {

        // get a collection object to work with
        DBCollection testCollection = db.getCollection("testCollection");

        // drop all the data in it

        // make a document and insert it
        BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database")
                                                                .append("count", 1)
                                                                .append("info", new BasicDBObject("x", 203).append("y", 102));


        // get it (since it's the only one in there since we dropped the rest earlier on)
        DBObject myDoc = testCollection.findOne();

        // now, lets add lots of little documents to the collection so we can explore queries and cursors
        for (int i = 0; i < 100; i++) {
            testCollection.insert(new BasicDBObject().append("i", i));
        System.out.println("total # of documents after inserting 100 small ones (should be 101) " + testCollection.getCount());

        // lets get all the documents in the collection and print them out
        DBCursor cursor = testCollection.find();
        try {
            while (cursor.hasNext()) {
        } finally {

        // now use a query to get 1 document out
        BasicDBObject query = new BasicDBObject("i", 71);
        cursor = testCollection.find(query);

        try {
            while (cursor.hasNext()) {
        } finally {

        // now use a range query to get a larger subset
        query = new BasicDBObject("i", new BasicDBObject("$gt", 50));  // i.e. find all where i > 50
        cursor = testCollection.find(query);

        try {
            while (cursor.hasNext()) {
        } finally {

        // range query with multiple constraints
        query = new BasicDBObject("i", new BasicDBObject("$gt", 20).append("$lte", 30));  // i.e.   20 < i <= 30
        cursor = testCollection.find(query);

        try {
            while (cursor.hasNext()) {
        } finally {

        // create an index on the "i" field
        testCollection.createIndex(new BasicDBObject("i", 1));  // create index on "i", ascending

        // list the indexes on the collection
        List<DBObject> list = testCollection.getIndexInfo();
        for (final DBObject o : list) {

        // See if the last operation had an error
        System.out.println("Last error : " + db.getLastError());

        // see if any previous operation had an error
        System.out.println("Previous error : " + db.getPreviousError());

        // force an error

        // See if the last operation had an error
        System.out.println("Last error : " + db.getLastError());


        // release resources


There are other parameters to connect the MongoDB Client.
 MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); specfied ip,port
  boolean auth = db.authenticate(myUserName, myPassword); if you need db authenciation
b)Authenticate as the user “user1” with a password of “password1”, defined in the “test” database
MongoCredential credential = new MongoCredential("user1", "password1".toCharArray(), "test");

MongoClient mongoClient = new MongoClient(new ServerAddress(server), Arrays.asList(credential));

1 comment:

  1. BlueHost is ultimately the best web-hosting provider with plans for any hosting needs.