Monday, November 2, 2015

MongoDB bulk upsert with java

I recently came up through the requirement for mongo db upsert with multiple documents in a single collection which should be transactional.

So I used BulkWriteOperation to achieve this requirement.

   1. Get the DBCollection

        private DBCollection getCollection() {
            MongoClient mongo;
            try {
                mongo = new MongoClient("localhost");
                DB db = mongo.getDB("test");
                return db.getCollection("employees");
            } catch (UnknownHostException e) {
                return null;
}
    }


2. Create Criteria to find the objects using Map:
     
     Map map = new HashMap();
      map.put("name", "anish");
      map.put("address", "kathmandu,nepal");
      map.put("phone", "9849243742");

3. Get DBObjects from the criteria, create WriteRequestBuilder

    DBCollection dbCollection = getCollection();
    DBObject dbObject = dbCollection.findOne(new BasicDBObject(map));
    BulkWriteRequestBuilder bulkWriteRequestBuilder = bulkWriteOperation.find(new         BasicDBObject(map));
    BulkUpdateRequestBuilder updateReqBuilder = bulkWriteRequestBuilder.upsert();

4. update request builder with new datas and then execute.

    updateReq.replaceOne(new BasicDBObject(map)
                .append("age", "25")
                .append("name", "anish manandhar")
                .append("address", "KTM,Nepal"))
                );
    }
    BulkWriteResult result = bulkWriteOperation.execute();
    System.out.println(result.getUpserts().size());

You can use BulkWriteResult's properties like modified, removed, upsert, inserted, matched etc for more information.
      
     

No comments:

Post a Comment