Monday, May 21, 2012

Querying and Inserting records into MongoDB using LoadRunner

This simple LR script inserts and retrieves a record from mongoDB. You can modify it to accommodate your own need.

Requirement:
Download Java driver for mongoDB and add it to the classpath in the java script.



import java.lang.String;
import java.net.UnknownHostException;
import java.util.Set;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

import lrapi.lr;
public class Actions
{ 
    static String HostName ="localhost";  
    static Integer Port = 27017;
    static String Username ="Harinder";
    static String Password ="Password";
    Mongo mDB;
    DB db;

 public int init() throws Throwable{
    try { 
        mDB= new Mongo( HostName , Port ); //connect to MongoDB using HostName and Port
        db = mDB.getDB("test"); // get test database from MongoDB
        boolean auth = db.authenticate(Username, Password.toCharArray()); //authenticate user access to test database
        if (auth = true) 
           lr.output_message("Successfully Authenticated");
        else
           lr.output_message("Incorrect Username/Password");

     }catch (UnknownHostException e) {
        e.printStackTrace();
    }
     return 0;
   }//end of init function

 public int action() throws Throwable {
     try { 
          InsertInToMongoDB("Harinder1", "Seera1", "ThisIsMongoDB1@gmail.com");
 
         }catch (MongoException e){
          e.printStackTrace();
         }

     try { 
         SearchMongoDB("Harinder");
 
         }catch (MongoException e){
          e.printStackTrace();
        }
 return 0;
 }//end of action function


 public int end() throws Throwable {
     mDB.close();
  return 0;
 }//end of end function


   public void InsertInToMongoDB(String FirstName, String LastName, String Email)
   { 
       // Get collection from mongoDB.
       // If collection doesn't exist, mongoDB will create it automatically
       DBCollection collection = db.getCollection("MyCollection");
       BasicDBObject document = new BasicDBObject();  // create a document to store key and value
       document.put("FirstName",FirstName);
       document.put("LastName", LastName);
       document.put("Email", Email);
       collection.insert(document);   //save the document into collection
   }


   public void SearchMongoDB(String FirstName)
   { 
       DBCollection collection = db.getCollection("MyCollection");
       BasicDBObject srchQuery = new BasicDBObject(); // search query
       srchQuery.put("FirstName", FirstName);
       DBCursor cur = collection.find(srchQuery); // query it
 
       // loop over the cursor and display the retrieved result
       while (cur.hasNext()) {
         System.out.println(cur.next()); //I am using it only for the blog purpose to show the output.
   }
 }
}

mongoDB output: