Prem
Prem

Reputation: 83

Parse JSON into a MONGODB docment

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.

Upvotes: 6

Views: 21910

Answers (3)

Armen Arzumanyan
Armen Arzumanyan

Reputation: 2043

I used google gson for convert pojo to json, and this is work perfect.

private final MongoCollection<Document> collection;

//my save
    String json = gson.toJson(data);//data is User DTO, just pojo!
    BasicDBObject document = (BasicDBObject) JSON.parse(json);
    collection.insertOne(new Document(document));

Java mongodb driver version is 3.4.2

Upvotes: 0

Ruthwik
Ruthwik

Reputation: 623

  • 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);

Upvotes: 7

jyemin
jyemin

Reputation: 3813

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

Upvotes: 9

Related Questions