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.
In MongoDB, you can import JSON files using mongoimport tool.
MongoDB Compass can import data into a collection from either a JSON or CSV file.
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.
Use the static parse(String json) method that's defined in the Document class.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With