Showing posts with label MongoDB. Show all posts
Showing posts with label MongoDB. Show all posts

Wednesday, May 16, 2018

Manual rollback with MongoDB

When there is a need to save different documents at the same time in microservices, or more specifically NoSql.
It is not an easy job, because NoSql does not support transaction like RDBMS.

The multiple phases commit in the previous post able to achieve the transaction-like behavior with MongoDB.

The code snippet below will be demonstrated by Play2.x, MongoDB, Morphia.


JsonNode json = request().body().asJson();
MyDocument md = Json.fromJson(json, MyDocument.class);
MyDocument mdCurrent = MyDocumentRepo.findMyDocumentById( md.getId() );

MyDocumentRepo.save( md );

boolean status = callNextService();

if(status == true) {
  // not doing anything
} else {
  // manually rollback the previous md
  MyDocumentRepo.save( mdCurrent );
}



Done!!

Friday, June 23, 2017

Saving and Updating a document with json in MongoDB

In MongoDB, we can use the same save(DBObject document) to save or update a json into MongoDB.


String jsonString = "{'Page':1,'Fruits':['apple','peach','pear']}";  // some json string
DBObject dbObject = (DBObject)JSON.parse(jsonString);

MongoClient mongo = new MongoClient( Arrays.asList(new ServerAddress("localhost", 27017)) );
DB db = mongo.getDB("myDB");
DBCollection collection = db.getCollection("myCollection");
collection.save(dbObject);



the save(DBObject document) will identify if this is new document,
it will perform insert
otherwise it will perform update.


Done!!

Thursday, April 20, 2017

How to query with Pattern / Case insensitive in mongoDB

 This following example is showing how to query the mongoDB with LIKE


BasicDBObject criteria = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
if(firstName != null && firstName.length() > 0) {

//            search the firstName field with case sensitive LIKE operator  
    obj.add(new BasicDBObject("firstName", Pattern.compile(firstName));
}
if(lastName != null && lastName.length() > 0) {

//            search the lastName field with case insensitive LIKE operator
    obj.add(new BasicDBObject("lastName", 
        java.util.regex.Pattern.compile(lastName, Pattern.CASE_INSENSITIVE)));
}        
if(obj != null && obj.size() > 0) {
    criteria.put("$and", obj);            
}




Done!!

Wednesday, March 29, 2017

How to convert DBCursor to JsonNode in Play

The code below only applicable when using mongoDB and Play framework together.


com.mongodb.util.JSON json =new JSON();
String serializedCursor = json.serialize(cursor);

com.fasterxml.jackson.databind.JsonNode jsonData = play.libs.Json.parse(serializedCursor);




Done!!

LinkWithin

Related Posts Plugin for WordPress, Blogger...