Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert json Object to Document in mongodb using java [duplicate]

Tags:

java

json

mongodb

I'm using the below sample json :

JSONObject json=new JSONObject();
            json.put("time_range", "22-23");
            json.put("flow_id", "786");

And trying to convert to Document as follows :

Document doc = (Document) JSON.parse(jsonlist.toString()); // conversion from json to Document

col.insertOne(doc); // inserting into Mongo collection

I'm facing the below error:

 java.lang.ClassCastException: com.mongodb.BasicDBObject cannot be cast to org.bson.Document    

Can anyone please help me out regarding this issue ...

like image 683
dev777 Avatar asked Aug 16 '16 08:08

dev777


People also ask

Is MongoDB document same as JSON?

Does MongoDB use BSON or JSON? MongoDB stores data in BSON format both internally, and over the network, but that doesn't mean you can't think of MongoDB as a JSON database. Anything you can represent in JSON can be natively stored in MongoDB, and retrieved just as easily in JSON.

How do I import a JSON file into MongoDB?

Open the Import Wizard. Then, choose JSON as the import format and click OK. Click on + to add JSON source documents, – to remove them, or the clipboard icon to paste JSON data from the clipboard.

Can I convert BSON to JSON?

Converting a BSON Object to a JSON StringUse the asString method to convert the BSON document to an extended JSON string. See http://docs.mongodb.org/manual/reference/mongodb-extended-json/ for more information on extended JSON.

What is JSON format in MongoDB?

JSON is a data format that represents the values of objects, arrays, numbers, strings, booleans, and nulls. The Extended JSON format defines a reserved set of keys prefixed with " $ " to represent field type information that directly corresponds to each type in BSON, the format that MongoDB uses to store data.


1 Answers

Try this

Document doc = Document.parse( jsonlist.toString() );
like image 88
Young Emil Avatar answered Sep 29 '22 17:09

Young Emil