Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON into a MONGODB docment

Tags:

java

mongodb

I am new to JAVA and MONGODB and have been learning both to try and understand if these technologies would meet my requirements for a product.

I am currently stuck in a point where I am not able to insert documents(records) from JAVA into my MONGODB collection.

I am using the new MONGODB version 3.0.

Code so far

MongoCollection<Document> coll = db.getCollection("Collection");
String json = "{'class':'Class10', 'student':{'name':'Alpha', 'sex':'Female'}, {'name':'Bravo', 'sex':'Male'}}";

I have found code to convert this to a DBObject type.

DBObject dbObject = (DBObject)JSON.parse(json);

But I guess the new version of MONGODB does not have the insert method but instead has the insertOne method.

coll.insertOne() requires that the input be in the Document format and does not accept the DBObject format.

coll.insertOne((Document) dbObject);

gives the error

com.mongodb.BasicDBObject cannot be cast to org.bson.Document

Can someone help me with the right type casting and give me a link where I could find and learn the same?

Regards.

like image 600
Prem Avatar asked May 28 '15 05:05

Prem


People also ask

Can we import JSON in MongoDB?

In MongoDB, you can import JSON files using mongoimport tool.

Can I import data into MongoDB?

MongoDB Compass can import data into a collection from either a JSON or CSV file.

What the difference between BSON and JSON in MongoDB?

BSON is nothing but Binary JSON i.e Binary JavaScript Object Notation. Unlike JSON, it is not in a readable format. It supports the embedding of documents and arrays within other documents and arrays. Like JSON, it is easy for machines to parse and generate.


2 Answers

Use the static parse(String json) method that's defined in the Document class.

like image 182
jyemin Avatar answered Oct 21 '22 14:10

jyemin


  • The problem is that you are using an older version(BasicDBObject) that is not compatible with version 3.0.

  • But there is a way for 2.0 users to use BasicDBObject.An overload of the getCollection method allows clients to specify a different class for representing BSON documents.

The following code must work for you.

MongoCollection<BasicDBObject> coll = db.getCollection("Collection", BasicDBObject.class);

coll.insertOne(dbObject);
like image 37
Ruthwik Avatar answered Oct 21 '22 13:10

Ruthwik