Tuesday, May 14, 2013



Connecting to the MongoDB server with Java API(Without Security)

MongoURI uri = new MongoURI("mongodb://ip_of_mongoDB_server");
Mongo mongo = (new Mongo.Holder()).connect(uri);

Getting a DataBase

DB db = mongoClient.getDB("dataBaseName");

Getting a Collection

DBCollection coll = db.getCollection("collectionName");

Inserting a document

BasicDBObject doc = new BasicDBObject("name", "MongoDB").
                              append("type", "database").
                              append("count", 1).
                              append("info", new BasicDBObject("x", 203).append("y", 102));

Finding first document in a collection

DBObject myDoc = coll.findOne();

Counting  document in a collection


Inserting multiple document 

for (int i=0; i < 100; i++) {
    coll.insert(new BasicDBObject("i", i));

Using cursor to get all documents

DBCursor cursor = coll.find();
try {
   while(cursor.hasNext()) {
} finally {

Getting a list of databases

MongoClient mongoClient = new MongoClient();

for (String s : m.getDatabaseNames()) {

MongoDB Recovery

  • Manually remove the lock file: sudo rm /var/lib/mongodb/mongod.lock
  • Run the repair script: sudo -u mongodb mongod -f /etc/mongodb.conf --repair.
    • You must run this command as the mongodb user. If you run it as root, then root will own files in /var/lib/mongodb/ that are necessary to run the mongodb daemon and therefore when the daemon trys to run later as the mongodb user, it won't have permissions to start. In that case you'll get this error: Unable to create / open lock file for lockfilepath: /var/lib/mongodb/mongod.lock errno:13 Permission denied, terminating.

    • On Ubuntu, you must specify the configuration file /etc/mongodb.conf using the -f flag. Otherwise it will look for the data files in the wrong place and you will see the following error: dbpath (/data/db/) does not exist, terminating.

  • Now you can start your MongoDB server with sudo start mongodb and verify it is running with sudo status mongodb and by trying to connect to it with mongo test.

Start/ Stop Mongo Server

Start : sudo start mongodb
Stop     :  sudo /etc/init.d/mongodb stop

Dump and Restore(Create backup and Restore from backup)

Create Dump : mongodump --db [databse name]
Here databse name is the name of the database that you need to backup.
This will create a dump folder of each collections in the BSON file format .
Restore : mongorestore --db [database name] --drop [source path]

Search Pattern (regex)

Using 'Terminal'
Eg: For finding the names with the letter 'D' from collection 'nameColl', use


Using Java API

collectionName.find(new BasicDBObject("key",java.util.regex.Pattern.compile(regex)));

Eg: Consider the same example above. Using Java API we can find the pattern matching as,BasicDBObject object = new BasicDBObject();

object.put("name", java.util.regex.Pattern.compile("D"));
DBCursor nameCur = nameColl.find(object);

Get last inserted records

Eg: For list the last entered name data in 'nameColl' can be list in terminal by type,

Search by ID

Using Terminal
Here 'Your_ID' can be replaced with your id to find the record it belongs.
Eg: db.nameColl.find({“_id”:ObjectId(“565564564asgf654”)})
Follow on Bloglovin

No comments:

Post a Comment

Total Pageviews