In the Java Mongo DB driver version 3 the API has changed as compared to the version 2. So a code like this does not compile anymore:
BasicDBObject personObj = new BasicDBObject();
collection.insert(personObj)
A Collection insert works only with a Mongo Document.
Dealing with the old code I need to ask the question:
What is the best way to convert a BasicDBObject to a Document?
BasicDBObject(Map map) Creates an object from a map. BasicDBObject(String key, Object value) Creates an object with the given key/value.
The MongoDB Legacy driver mongodb-driver-legacy is the legacy synchronous Java driver whose entry point is com. mongodb. MongoClient and central classes include com. mongodb. DB , com.
You can update a single document using the updateOne() method on a MongoCollection object. The method accepts a filter that matches the document you want to update and an update statement that instructs the driver how to change the matching document.
We Can Convert BasicDBObject
to Document
by the following way
public static Document getDocument(DBObject doc)
{
if(doc == null) return null;
return new Document(doc.toMap());
}
as Document
itself is an implementation of Map<String,Object>
.
and BasicDBObject
can be too be catch in DBObject
as BasicDBObject
is an implementation of DBObject
.
@Black_Rider for you too
The Document is very similar to the BasicDBObject. I am not quite sure what you are referring to as a way to convert BasicDBObjects to Documents, but the Document object provides some very useful methods.
Document.parse(string) will return a Document if you feed it in a JSON string.
Document.append("key", Value) will add to the fields of a Document.
As for the code in your post, this should compile with version 3:
Document personObj = new Document();
collection.insertOne(personObj)
See
Java Driver 3.0 Guide
and
MongoDB Java Driver 3.0 Documentation
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