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!!

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...