Monday, June 30, 2014

Collect your linkedin socail contact on MongoDb

I haven;t written my blog for sometimes.These days I write a simple application to collect my Linked social contact into MongoDB from BlueMix.I will share my experience.I put my code at jazzhub,you can get complete code from here.

LinkedIn  is a business-oriented social networking service.People can know other one's working status and job info from this website.Sometimes poeple want to save his connection into his database for information collection.

When you use my application to deploy on the bluemix,the first things you need to do you need to apply for a key for API usage.You can apply the key from

You can fill the below form,after that you can get the oath key.

The key class is  SocialServlet .


import java.util.List;
import java.util.Map;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.cloudfoundry.runtime.env.CloudEnvironment;


import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
public class SocialServlet extends HttpServlet implements Servlet {

private static final String CONSUMER_KEY_OPTION = "";
private static final String CONSUMER_SECRET_OPTION = "";
private static final String ACCESS_TOKEN_OPTION = "";
private static final String ACCESS_TOKEN_SECRET_OPTION = "";
private static final int QUERY_MAX = 20;

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
String connURL = getServiceURI();
MongoClient mongoClient = new MongoClient(new MongoClientURI(

ClientFactory client = new ClientFactory(
final LinkedInApiClient accessApi = client.getFactory()
long timeStart = System.currentTimeMillis();
System.out.println("Process start..");
ProfileAPI profileAPI = new ProfileAPI(accessApi);
DB mongoDB = mongoClient.getDB("db");
DBCollection usersProfile = mongoDB.getCollection("usersProfile");
BasicDBObject userDocument = new BasicDBObject();
int countQuery = 0;
Person profile = profileAPI.getProfile();
ConnectionsAPI connection = new ConnectionsAPI(accessApi);
List<Person> peopleConnection = connection.getConnections()
String parentId = profile.getId();
while (SocialServlet.QUERY_MAX > countQuery++) {
userDocument.put("lastName", profile.getFirstName());
if (profile.getLocation() != null) {
System.out.println("lastName is"
+ profile.getLocation().getName());
System.out.println("lastName is" + profile.getFirstName());
userDocument.put("lastName", profile.getLastName());
System.out.println("lastName is" + profile.getLastName());
userDocument.put("headline", profile.getHeadline());
System.out.println("headline is" + profile.getHeadline());
userDocument.put("summary", profile.getSummary());
System.out.println("summary is" + profile.getSummary());
userDocument.put("profileUrl", profile.getPublicProfileUrl());
System.out.println("profile url"
+ profile.getPublicProfileUrl());
userDocument.put("profileId", profile.getId());
userDocument.put("birthdate", profile.getDateOfBirth());
userDocument.put("profile birthdate", profile.getDateOfBirth());
System.out.println(" birthdate" + profile.getDateOfBirth());
parentId.equals(profile.getId()) ? "" : parentId);;
if (peopleConnection.size() > 0
&& peopleConnection.size() > countQuery) {
profile = profileAPI.getProfile(peopleConnection.get(

} else {
countQuery = SocialServlet.QUERY_MAX;

long timeEnd = System.currentTimeMillis();
.println("Your Linked social contact has been saved in the mongodb");
.println("Time schedule " + (timeEnd - timeStart) + " ms");

} catch (Exception e) {
out.println("Failed: " + e.getMessage());

public String getServiceURI() throws Exception {
CloudEnvironment environment = new CloudEnvironment();
if (environment.getServiceDataByLabels("mongodb").size() == 0) {
throw new Exception("No MongoDB service is bund to this app!!");

Map credential = (Map) ((Map) environment.getServiceDataByLabels(
System.out.println(" I have get credentials url"+(String) credential.get("url"));
return (String) credential.get("url");


Notes:You need to add cloudfoundry.jar to get the MongoDB credential url.In order to use Linked API,you need to download the api jar from the

After export the war from the eclipse project ,you can use cf command to deploy this way to the BlueMix.
Use command like:
cf p Mysocailcontact -p social.war 

Then bind mongodb service to the Mysocailcontact app.

After execute the below url

You can find the log we wrote in the code on the bluemix.

Login into the Mongo DB console on the bluemix,you can find the record on that db,the record will save my connection from this website.

Wednesday, June 25, 2014

java based MonogoDB application on BlueMix

NoSQL databases are finding significant and growing industry use in big data and real-time web applications,it provide way to save unstructured data.
Use Cases of ever increasing unstructured data
        750 million users are active , 1 in 3 Internet users have a Facebook account
        More than 30 billion pieces of content (web links, news stories, blog posts, notes, photo albums, etc.) shared each month.
        Holds 30PB of data for analysis, adds 12 TB of compressed data daily
        200 million users, 200 million daily tweets
        1.6 billion search queries a day
        7 TB data for analysis generated daily

Here is a simple example showing how to save data to mongodb from java web application on BlueMix

1.Get the code from
2. Unzip the code to your driver

3.If you have install maven,use mvn package to generate the war file.

4.Switch the dos command and use below command to push you war to the bluemix.

   cf p javamongodb  -p java-mongodb-sample.war
5.Create your mongodb service
cf create-service mongodb 100 mongodbLinedIN

6.Bind your mongodb service

cf bind-service javamongodb mongodbLinedIN

7.use cf push to make the env effect.

8.Launch the url of the app,you will see the data has been inserted into Mongodb.

Detail code: MainServlet ,we need to add mogodb ,cloudfoundry lib on the classpath


import java.util.*;

import org.cloudfoundry.runtime.env.*;

import javax.servlet.*;
import javax.servlet.http.*;

import com.mongodb.*;

public class MainServlet extends HttpServlet implements Servlet {

  protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
        String connURL = getServiceURI();
        MongoClient mongo = new MongoClient(new MongoClientURI(connURL));

        DB db = mongo.getDB("db");

        DBCollection table = db.getCollection("user");

        BasicDBObject document = new BasicDBObject();
        document.put("name", "Tom");
        document.put("age", 30);
        document.put("createdDate", new Date());

        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("name", "Tom");

        DBCursor cursor = table.find(searchQuery);

        while (cursor.hasNext()) {
            out.println( "Inserted: " +;

        BasicDBObject query = new BasicDBObject();
        query.put("name", "Tom");

        BasicDBObject newDocument = new BasicDBObject();
        newDocument.put("name", "Tina");

        BasicDBObject updateObj = new BasicDBObject();
        updateObj.put("$set", newDocument);

        table.update(query, updateObj);

        BasicDBObject searchQuery2 = new BasicDBObject().append("name", "Tina");

        DBCursor cursor2 = table.find(searchQuery2);

        while (cursor2.hasNext()) {
            out.println( "Updated: " +;


    } catch (Exception e) {
        out.println("Failed: " + e.getMessage());

  public String getServiceURI() throws Exception {
    CloudEnvironment environment = new CloudEnvironment();
    if ( environment.getServiceDataByLabels("mongodb").size() == 0 ) {
        throw new Exception( "No MongoDB service is bund to this app!!" );

    Map credential = (Map)((Map)environment.getServiceDataByLabels("mongodb").get(0)).get( "credentials" );

    return (String)credential.get( "url" );


Thursday, June 19, 2014

Cloud Foundry vs OpenStack

Cloud Foundry is an open platform as a service, providing a choice of clouds, developer frameworks and application services. Initiated by VMware, with broad industry support, Cloud Foundry makes it faster and easier to build, test, deploy and scale applications. It is an open source project and is available through a variety of private cloud distributions and public cloud instances, including

OpenStack is a global collaboration of developers and cloud computing technologists producing the ubiquitous open source cloud computing platform for public and private clouds. The project aims to deliver solutions for all types of clouds by being simple to implement, massively scalable, and feature rich. The technology consists of a series of interrelated projects delivering various components for a cloud infrastructure solution.

Cloud Foundry is PAAS,while OpenStack  is IAAS.You can deploy cloud foundry on the openstack.You can watch this video to know the relationships between them.

Monday, June 16, 2014

Learn open source from codeschool

BlueMix platform support lots of open source language,most of developers might master 2-3 language,but if I need to learn some new languages quickly,if there any place for me to learn?

These days I am fascinated with codeschool website.It provides lots of course for you to study and most of them are free.It is an online learning destination for existing and aspiring developers that teaches through entertaining content.

For example if you want to learn git, you can visit this link to use interactive way to study it.It provide the simulate env ,so we don;t need to install anythings on your local side.

The below are part of course provide in this website.Just enjoy it.

Saturday, June 14, 2014

Manage MySql,PostgreSQL on the BlueMix

Actually BlueMix don;t provide the solution to operate   db like mysql,mongodb,PostgreSQL etc on the web UI.When people develop their application usually will create db or insert data for these open source db on the BlueMix.So we need a solution to manage these db on the BlueMix.I have already discussed about to maintain mongodb on the BlueMix in the previous post.Today I will talked about how to use manage mysql on the BlueMix.

Deploy phpMyAdmin on BlueMix

phpMyAdmin is a free software tool written in php, intended to handle the administration of MySQl over the Web. phpMyAdmin supports a wide range of operations on MySQL, MariaDB and Drizzle. Frequently used operations (managing databases, tables, columns, relations, indexes, users, permissions, etc) can be performed via the user interface, while you still have the ability to directly execute any SQL statement.

In the BlueMix category,we don;t have php runtime support that.So we will use php buildback to support that.I list the most import steps for you .

1.Since we need to use cf tool to deploy on the BlueMix,you need to download and install it from github.

2.We use cf command or web console to create our mysql service.Before create the service,make sure you have use cf login -a command to login into it.
create the MySQL service that the application will use. The command syntax is:


The service name is mysql, the plan is 100, and the service instance name is mysql_NMU. So you'll create your MySQL service like this:

cf create-service mysql 100 mysql_NMU

Here I create mysql service name is called mysql_NMU

3.The next step you need to download or clone the phpMyAdmin package from github from below address
4.After you donwoload the installation package and open the htdocs\ file.
Located the line 28,change 'cleardb-n/a' to 'mysql-5.5' .Below is the code after change.

 * Read MySQL service properties from _ENV['VCAP_SERVICES']
$services = json_decode($_ENV['VCAP_SERVICES'], true);
$service = $services['mysql-5.5'][0]; // pick the first service

4. Since we don;t want use the manifest.yml shipped in the default file,so we can use below command to push on the BlueMix.

cf push phpmyadminbluemix -b -m 128M --no-manifest --no-start

Bind previous created mysql service
cf bind-service phpmyadminbluemix  mysql_NMU

The we can start our application use below command

 cf start phpmyadminbluemix

5.After start the app,we need to use mysql credential to login into it.You can double click the application,click the runtime menu and find user name and password from Environment Variables.

6.Launch the url from the,you can see below login screenshot.

7.Use the username and password provide by step5,you can login into it and maintain the mysql on the Cloud.

Deploy WebSQL on the BlueMix

WebSQL is the ultimate desktop replacement for managing your MySQL databases over the web. With interface that works just like your favourite desktop applications, you don't need to keep switching over webpages to get simple things done. Just login to your database and manage your database as if your are working on your desktop.It support MySQL, SQLite and PostgreSQL three dbs.

You can download the latest package from

Deploy on the BlueMix for this php based application i same with phpMyAdmin.So I don't want to repeat the same steps here.But one place you might need to change on you side.Open the servers.php in the config foler.Change the code like below.If you want to manage PostgreSQL you can uncomment the line ,and comment mysql serice line for that.
* Read MySQL service properties from _ENV['VCAP_SERVICES']
$services = json_decode($_ENV['VCAP_SERVICES'], true);
$service = $services['mysql-5.5'][0]; // if you choose  the mysql service
       //$service = $services['postgresql-9.1'][0];//if use choose the postgresql-9.1
$host = $service['credentials']['hostname'];

$SERVER_LIST = array(
'MySQL'           => array(
                            'host'     => $host. ':' . $port,
                            'driver'   => 'mysql5'
/* 'Localhost PostgreSQL'     => array(
                            'host'     =>$host. ':' . $port,
                            'driver'   => 'pgsql'

If your deployment on BlueMix is successful,you should see below screenshot.

So from below two apps deployment guide ,you can try similar solution with me to support other db on BlueMix.

Wednesday, June 11, 2014

Send email use Node.js on BlueMix

There are many ways to send eamil use node.js.Today I will introduce three ways to send email.

1.Nodemailer is an easy to use module to send e-mails with Node.JS (using SMTP or sendmail or Amazon SES or even your own method) and is unicode friendly - You can use any characters you like.

The whole development is very easy.
a)Install Nodemailer
> npm install nodemailer
b)Write below code
var nodemailer = require("nodemailer");

var smtpTransport = nodemailer.createTransport("SMTP",{
   service: "Gmail",
   auth: {
       user: "",
       pass: "XXX"

var mail = {
    from: "",
    to: "",
    subject: "Send Email Using Node.js",
    text: "Node.js New world for me",
    html: "<b>Node.js New world for me</b>"

smtpTransport.sendMail(mail, function(error, response){
        console.log("Message sent: " + response.message);


c) In node.js enviroment run nodeemail.js,you will see the email has been sent.

d)You can install it from npm. Add a dependency to your package.json and run npm install
package.json contents:
"dependencies": {
   "nodemailer": "0.3.29"

2. Since first way we need to use smtp and also need authenciation,sometimes we don;t have smtp server provided,so we need to use 'sendmail module to handle it .The code is more easy.

sendmail = require('sendmail')();

    from: '',
    to: '',
    subject: 'test sendmail',
    type: 'text/html',
    content: '<h3>hello</h3><p>Hey guys</p>
  }, function(err, reply) {
    console.log(err && err.stack);
Also you can reference this open source code at github.

3.Using SendGrid service,you can reference below link.

Tuesday, June 10, 2014

SoftLayer,competitive ISAS

SoftLayer operates a global cloud infrastructure platform built for Internet scale. Headquartered in Dallas and with an infrastructure spanning data centers in the United States, Asia and Europe, SoftLayer’s unified architecture provides unparalleled performance and control, with a full-featured API andsophisticated automation controlling a flexible platform that seamlessly integrates physical and virtual devices, allowing customers to deploy public cloud instances, bare metal servers and turnkey private clouds in real-time, and a global network for secure, low-latency communications. With 100,000 serversunder management, SoftLayer is the largest privately held infrastructure-as-a-service provider in the world with a portfolio of leading-edge customers from Web startups to global enterprises.It is accquired by IBM in 2013.

Now IBM provide the SoftLayer 30-day free trial for enterprise.You can take chance to have a trial at here.

Most of us are not famliar with  SoftLayer technoledge.What SoftLayer can bring us?Below video the SoftLayer CEO will tell you more details about his company and their business.

What makes SoftLayer different? Softlayer differentiates itself along three main axes – Workload I/O intensity, infrastructure control.

What kind of detail service they provide and what is thier feature? If you have seen the below screenshot you might understand it.Everything starts from the physical server based on the x86 platform.  From this core platform your able to order bare metal servers, private clouds (hyper-visors), virtual servers as well as HPC servers all from the portal and any of these servers can be interconnected with each other.

Also SoftLayer provide a web protal for user to manage his cloud on the site.

Predictable Billing: With SoftLayer you get services on a monthly or hourly contract. No long term commitments or surprise usage fees.
This allows you to order services on demand to meet your current workload requirements.
Many competitors add charges for the resources you use.  For example: compute cycles per second, or bandwidth usage for inbound and outbound.  Our systems come with 5TB (bare metal) and 1TB bandwidth outbound and all private network traffic and public inbound traffic is unmetered.  Resources are not shared so you can use 100% of the resources you purchased without being billed anything extra.
Many gaming companies come to us not only for our performance but because they can budget their IaaS needs much easier even when workloads increase.
Price is inclusive of support as well.  You can contact a 24/7 support personnel via ticket, chat or voice anytime of the day for no extra cost.  Many providers will charge extra or not provide any support unless you are one of their primary accounts.

If  you are interested it,you can start to apply for a trial first,

Monday, June 9, 2014

Does BlueMix support Spring?

Before Write this topic,I got news for IBM site,the commercial BlueMix will be release at the end of June. Most service IBM provided are free of charge,you only need pay what use part of runtime enviroment fee.

 The Spring Framework is an open source application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform.Spring helps development teams everywhere build simple, portable,fast and flexible JVM-based systems and applications.

In order to demo the ability of the BlueMix ability we use the project on github.You can download it from
After download the package and unzip it and you should see the below strcture.
 Since it provide  a project object model (POM) xml file, we can use Maven to manage a project's build, reporting and documentation from a central piece of information. You can use maven to build the project .
You can use mvn package under the project strcutre.
It will generate hello-spring-env.war.So you can use cf command tool to publish this to the BlueMix,
For example we can use below command to push your app to the BlueMix.We bing a mysql service to our app,so the env will include the mysql service.
cf create-service mysql 100 mysql_NMU
cf p SpringSample -p hello-spring-env.war
cf bind-service SpringSample mysql_NMU

After deployment,you can see the result through the below url.You can mysql service is in the VCAP_SERVICE.
Also we can deploy the app in the eclipse,I left a eclipse strctrue for your reference.We can use cloundry plug-in to deploy it to the BlueMix side.

Friday, June 6, 2014

Cloud9 IDE , write your code on the cloud

Cloud9 IDE enables developers around the world to edit the same code and chat together in realtime. Your team and peers share in incredible productivity and higher quality code - no matter where they are.It is an online development environment for Javascript and Node.js applications as well as HTML, CSS, PHP, Java, Ruby and 23 other languages.You can even deploy your application to the PAAS like openshift,Heroku,Window Azure Cloud.As I know IBM Bluemix will be added it soon.

I registered a trail account to experience features for online cloud IDE.When you create a project workspace,it will provide some language template for you choose,since my favorite language,so I choose Node.js.

It will automatic create node.js sample project for you.You can directly run the server.js from the project workspace.Through the console ,you can launch the url from the console to start the node.js application .

So this tool you don;t need install node.js run time environment,it will automatic provide for you.Also it provide a debug tool for node.js.

Cloud9 IDE also provide the option for you deploy you application to the PAAS.
If you are a node,js programmer,I strongly suggest you to use this tool to deploy your application on the cloud.

Thursday, June 5, 2014

Getting Started with the IBM Internet of Things Cloud

What is the  Internet of Things Cloud ? The Internet of Things (IoT) is a scenario in which objects, animals or people are provided with unique identifiers and the ability to automatically transfer data over a network without requiring human-to-human or human-to-computer interaction. IoT has evolved from the convergence of wireless technologies, micro-electromechanical systems (MEMS) and the Internet.

You can learn more detail in the below youtube video.

So what is the  IBM Internet of Things Cloud? What is the relationship with BlueMix?Don;t worry,I will show some screenshot,you might understand it.

•Connect–Easily Register and connect “things” through a UI or APIs
•Collect–Collect and manage a time series view of data from “things”
•Assemble–Visually assemble events from things into logic flows
•Manage–Manage “thing” connections and subscriptions
•Build–Create applications that directly interact with connected “things”

IoT Cloud Quickstart is a tool to let embedded device developers connect
to the IoT and see data from their device, and to provide data for IoT application
developers to use.

  • It is not intended for production use.
  • It is a free service, there is no device or user registration step, and all data sent to
  • the Quickstart cloud could potentially be viewed by any internet user. 

IBM also provide Node-RED’s cool GUI for the Internet of Things.If you are interested you can visit BlueMix provide Node-Red service for user to use that .

Wednesday, June 4, 2014

ODM8.5.1 new Decision Engine

I noticed that BlueMix provide rule service is based on ODM8.5.1.It provide a new Decision Engine to help improve load time and execution time of decision services within Decision Server.But few people know how to use it.So today I just give a short introduction for you. ODM8.5.1  provide three rule engines, classic rule engine,decsion engine with intermddiate code,decision engine with java byte code.
Based on the official document it said:
The decision engine compiles rule artifacts into an archive that contains compiled and optimized code that becomes executable when translated to Java bytecode.
In comparison, a ruleset that is built with the classic rule engine contains a set of textual files that must be parsed before any compilation and optimization. Parsing, compiling and optimizing code are demanding tasks when you load a ruleset.
Therefore, the ruleset loading in the decision engine is faster because no code is parsed or interpreted at run time. All the code is already compiled (to intermediate code or Java bytecode) and fully optimized for rule execution.

So how do we choose use which rule engine,it is very simple.Open the rule designer,choose rule project -->Ruleset Build Mode-->Choose Decision engine.
So when you export you ruleset ,you can choose use java byte code for decision engine or not.

For the ruleset archive ,their might be different file structure.
The ruleset archive .jar file contains the rules in IRL text files.(CRE)The ruleset archive .dsar file consists of binary files that contain execution code for the rules and ruleflows.(DE)

Also for Decision Engine,you might need another API to invoke the rule engine,so the POJO code invoke classic rule engine might not work for Decision Engine,since if you work on the BlueMix rule service,you can use HTDS or rule rest api to invoke the rules,so you can avoid some unfamiliar DE java API to do that.

Tuesday, June 3, 2014

Ten minutes to learn WebSphere Liberty Profile Server

Liberty for Java™ applications on Bluemix are powered by the IBM WebSphere Liberty Buildpack. The Liberty profile is a highly composable, fast-to-start, dynamic application server runtime environment. It is part of IBM WebSphere Application Server v8.5.5.

If you are a newbie for the WAS Liberty Profile Server,you can watch the below  video to learn about it.
You can learn the its feature from below screenshot.

The whole installation is very simple. Open the Eclipse,Click  Help > Eclipse MarketPlace,in the search bar enter  liberty and click search,then click install button.

After installation and restart the eclipse,you can find it appear at below screenshot.
You can create liberty server through server-->Server Run time Environment,add WebSphere Liberty Profile to install runtime environment.
There are two ways to install
1. Visit site,download Liberty çš„installation files,Liberty installation size is less 50M,unzip your installation package to one specified path,then point to the specified path as your  run time enviorment path.
2. Follow  above screenshot Download or install link,you need to online download a liberty server environment
When you finish the configuration,you should see the liberty server in the below screenshot.

Double Click the Server Configuration,You can see the server.xml.It is the core part of the liberty.All your configuration is through this file.

<server description="new server"> 
    <!-- Enable features --> 

    <httpEndpoint id="defaultHttpEndpoint"
                  httpsPort="9443" /> 


You can also use GUI to config this file.

The default config only support jsp feature,you can add more features to support.

Application Deployment

Open your liberty installation folder <Liberty_Install_dir>\usr\servers\server_name,you can see below structure.The application configuration files will  be default put under apps folder.Also you can directly put the war files into the dropins folder,when start the liberty server,it will scan these two folder and automatic start the application from these two folders.

If you want to learn more detail info about how to develop the application on was liberty,I suggest you to read WebSphere Application Server Liberty Profile Guide for developers

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