Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a BasicDBObject to a Mongo Document with the Java Mongo DB driver version 3?

Tags:

java

mongodb

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?

like image 592
Alex Avatar asked Aug 12 '15 14:08

Alex


People also ask

What is BasicDBObject?

BasicDBObject(Map map) Creates an object from a map. BasicDBObject(String key, Object value) Creates an object with the given key/value.

What is MongoDB driver legacy?

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.

How do I update a MongoDB file in Java?

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.


2 Answers

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

like image 84
Shashank Avatar answered Sep 30 '22 07:09

Shashank


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

like image 43
dbenson Avatar answered Sep 30 '22 07:09

dbenson