How to insert a nested JSON string into mongodb?
-
Data = {'name' : 'Jack', 'age' : '30'} DBObject dbObject = (DBObject) JSON.parse(Date); JSON in string format is converted/parsed to a DBObject and inserted into the db but when there is a nested json like Data = {'name' : 'Jack', 'age' : '30', 'info' : {'dob' : '11-04-2000', 'doj' : '9-9-2012'}} I am getting com.mongodb.util.JSONParser.parseString
-
Answer:
Following is the code to insert your sample json string or any other string in mongo db : try { MongoClient client = new MongoClient(new ServerAddress("localhost", 27017)); DB db = client.getDB("test"); db.requestStart(); try{ db.requestEnsureConnection(); DBCollection users = db.getCollection("test"); String ds = "{'name' : 'Jack', 'age' : '30', 'info' : {'dob' : '11-04-2000', 'doj' : '9-9-2012'}} "; users.insert((DBObject) JSON.parse(ds)); } finally{ db.requestDone(); } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } As you can see its a very simple process. where you just have to parse the json string , cast it to a DBObject and insert it into the collection.
Rahul Verma at Quora Visit the source
Related Q & A:
- How to query a nested document in mongo?Best solution by Stack Overflow
- How to access a nested function from another nested function in javascript?Best solution by devarticles.com
- How long is a piece of string?Best solution by Yahoo! Answers
- How to insert a picture into email?Best solution by Yahoo! Answers
- How to insert a date variable in java?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.