Reputation: 808
Is there a simple way to convert Simple POJO to org.bson.Document?
I'm aware that there are ways to do this like this one:
Document doc = new Document();
doc.append("name", person.getName()):
But does it have a much simpler and typo less way?
Upvotes: 21
Views: 51012
Reputation: 29
If you use Spring Data MongoDB with springboot, MongoTemplate has a method to do this well.
Here's a sample.
1.First autowire the mongoTemplate in spring boot project.
@Autowired
MongoTemplate mongoTemplate;
2.Use mongoTemplate in your service
Document doc = new Document();
mongoTemplate.getConverter().write(person, doc);
In order to do this, you need config your pom file and yml to inject mongotemplate
pom.xml
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>2.1.10.RELEASE</version>
</dependency>
application.yml
# mongodb config
spring:
data:
mongodb:
uri: mongodb://your-mongodb-url
Upvotes: 2
Reputation: 1
No i think it can be usefull for bulkInsert. I think bulkInsert cannot work with pojo (if i'm not mistaken). If someone know how to user bulkInsert
Upvotes: -2
Reputation: 2005
I don't know your MongoDB version. But now-a-days, there is no need to convert Document to POJO or vice versa. You just need to create your collection depending on what you want to work with, Document or POJO as follows.
//If you want to use Document
MongoCollection<Document> myCollection = db.getCollection("mongoCollection");
Document doc=new Document();
doc.put("name","ABC");
myCollection.insertOne(doc);
//If you want to use POJO
MongoCollection<Pojo> myCollection = db.getCollection("mongoCollection",Pojo.class);
Pojo obj= new Pojo();
obj.setName("ABC");
myCollection.insertOne(obj);
Please ensure your Mongo DB is configured with proper codecregistry if you want to use POJO.
MongoClient mongoClient = new MongoClient();
//This registry is required for your Mongo document to POJO conversion
CodecRegistry codecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
MongoDatabase db = mongoClient.getDatabase("mydb").withCodecRegistry(codecRegistry);
Upvotes: 5
Reputation: 86
If you are using Morphia, you can convert a POJO to document using this piece of code.
Document document = Document.parse( morphia.toDBObject( Entity ).toString() )
If you are not using Morphia, then you can do the same by writing custom mapping and converting the POJO into a DBObject and further converting the DBObject to a string and then parsing it.
Upvotes: 0
Reputation: 345
Currently Mongo Java Driver 3.9.1 provide POJO support out of the box
http://mongodb.github.io/mongo-java-driver/3.9/driver/getting-started/quick-start-pojo/
Let's say you have such example collection with one nested object
db.createCollection("product", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "description", "thumb"],
properties: {
name: {
bsonType: "string",
description: "product - name - string"
},
description: {
bsonType: "string",
description: "product - description - string"
},
thumb: {
bsonType: "object",
required: ["width", "height", "url"],
properties: {
width: {
bsonType: "int",
description: "product - thumb - width"
},
height: {
bsonType: "int",
description: "product - thumb - height"
},
url: {
bsonType: "string",
description: "product - thumb - url"
}
}
}
}
}
}});
1. Provide a MongoDatabase bean with proper CodecRegistry
@Bean
public MongoClient mongoClient() {
ConnectionString connectionString = new ConnectionString("mongodb://username:[email protected]:27017/dbname");
ConnectionPoolSettings connectionPoolSettings = ConnectionPoolSettings.builder()
.minSize(2)
.maxSize(20)
.maxWaitQueueSize(100)
.maxConnectionIdleTime(60, TimeUnit.SECONDS)
.maxConnectionLifeTime(300, TimeUnit.SECONDS)
.build();
SocketSettings socketSettings = SocketSettings.builder()
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.build();
MongoClientSettings clientSettings = MongoClientSettings.builder()
.applyConnectionString(connectionString)
.applyToConnectionPoolSettings(builder -> builder.applySettings(connectionPoolSettings))
.applyToSocketSettings(builder -> builder.applySettings(socketSettings))
.build();
return MongoClients.create(clientSettings);
}
@Bean
public MongoDatabase mongoDatabase(MongoClient mongoClient) {
CodecRegistry defaultCodecRegistry = MongoClientSettings.getDefaultCodecRegistry();
CodecRegistry fromProvider = CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build());
CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(defaultCodecRegistry, fromProvider);
return mongoClient.getDatabase("dbname").withCodecRegistry(pojoCodecRegistry);
}
2. Annotate your POJOS
public class ProductEntity {
@BsonProperty("name") public final String name;
@BsonProperty("description") public final String description;
@BsonProperty("thumb") public final ThumbEntity thumbEntity;
@BsonCreator
public ProductEntity(
@BsonProperty("name") String name,
@BsonProperty("description") String description,
@BsonProperty("thumb") ThumbEntity thumbEntity) {
this.name = name;
this.description = description;
this.thumbEntity = thumbEntity;
}
}
public class ThumbEntity {
@BsonProperty("width") public final Integer width;
@BsonProperty("height") public final Integer height;
@BsonProperty("url") public final String url;
@BsonCreator
public ThumbEntity(
@BsonProperty("width") Integer width,
@BsonProperty("height") Integer height,
@BsonProperty("url") String url) {
this.width = width;
this.height = height;
this.url = url;
}
}
3. Query mongoDB and obtain POJOS
MongoCollection<Document> collection = mongoDatabase.getCollection("product");
Document query = new Document();
List<ProductEntity> products = collection.find(query, ProductEntity.class).into(new ArrayList<>());
And that's it !!! You can easily obtain your POJOS
without cumbersome manual mappings
and without loosing ability to run native mongo queries
Upvotes: 26
Reputation: 569
You can use Gson
and Document.parse(String json)
to convert a POJO to a Document
. This works with the version 3.4.2 of java driver.
Something like this:
package com.jacobcs;
import org.bson.Document;
import com.google.gson.Gson;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoLabs {
public static void main(String[] args) {
// create client and connect to db
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("my_db_name");
// populate pojo
MyPOJO myPOJO = new MyPOJO();
myPOJO.setName("MyName");
myPOJO.setAge("26");
// convert pojo to json using Gson and parse using Document.parse()
Gson gson = new Gson();
MongoCollection<Document> collection = database.getCollection("my_collection_name");
Document document = Document.parse(gson.toJson(myPOJO));
collection.insertOne(document);
}
}
Upvotes: 17
Reputation: 132
The point is, that you do not need to put your hands on org.bson.Document.
Morphia will do all that for you behind the curtain.
import com.mongodb.MongoClient;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.DatastoreImpl;
import org.mongodb.morphia.Morphia;
import java.net.UnknownHostException;
.....
private Datastore createDataStore() throws UnknownHostException {
MongoClient client = new MongoClient("localhost", 27017);
// create morphia and map classes
Morphia morphia = new Morphia();
morphia.map(FooBar.class);
return new DatastoreImpl(morphia, client, "testmongo");
}
......
//with the Datastore from above you can save any mapped class to mongo
Datastore datastore;
final FooBar fb = new FooBar("hello", "world");
datastore.save(fb);
Here you will find several examples: https://mongodb.github.io/morphia/
Upvotes: 3