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 http://www.mongodb.org/downloads
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

ParameterDescription
--bind_ipbind IP,if bind 127.0.0.1,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

>db.userdetails.insert(document)

g)Check db collection records
>db.userdetails.find();

MongoDB with the Java API

You must download the MongoDB driver from below address
https://github.com/mongodb/mongo-java-driver/downloads

Sample code fro QuickTour.java

package com.ibm.bluemix;
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.net.UnknownHostException;
import java.util.List;
import java.util.Set;

/**
 * The tutorial from http://www.mongodb.org/display/DOCS/Java+Tutorial.
 */
public class QuickTour {
    // CHECKSTYLE:OFF
    /**
     * 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) {
            System.out.println(s);
        }

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

        // drop all the data in it
        testCollection.drop();

        // 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));

        testCollection.insert(doc);

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

        // 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()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }

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

        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }

        // 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()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }

        // 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()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }

        // 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) {
            System.out.println(o);
        }

        // 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
        db.forceError();

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

        db.resetError();

        // release resources
        mongoClient.close();
    }
    // CHECKSTYLE:ON
}

Notes:

There are other parameters to connect the MongoDB Client.
a)
 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));


No comments:

Post a Comment