Sunday, March 9, 2014

MongoDB : Insert a DBRef for a given id in a DBCollection

Following example describes the use of DBRefs in a collection. DBRef can be used to define a reference to record in a different collection. This is similar to Foreign Key in Oracle but the advantage of MongoDB is its flexibility to allow DBRef from different collections in same column.

In the example below, a new employee record has to be added to HR department.

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

....


    // Get the Database
    DB employeeDB = mongoClient.getDB("employeeDB");

    /* Get the Database Reference for the HR department. The HR is primary key/_id in department table. */
    DBRef departmentHR = new DBRef(employeeDB, "department", "HR");

    // Get the Employee Collection
    DBCollection employeeRecords = employeeDB.getCollection("employee");

                                   
   // Create a Database object to insert new Employee 
   BasicDBObject newEmployee = new BasicDBObject();
   newEmployee.put("employee_id", "1234");


   // Add the DBRef for HR department to this employee
   newEmployee.put("department_id", departmentHR);

   //Insert a new record for Employee.
   employeeRecords.insert(newEmployee);


Please leave a comment for queries/suggestions.

No comments:

Post a Comment