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?
//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.
A quick look at how to convert a POJO from/to a Map<K, V> with Jackson: // Create ObjectMapper instance ObjectMapper mapper = new ObjectMapper(); // Converting POJO to Map Map<String, Object> map = mapper. convertValue(foo, new TypeReference<Map<String, Object>>() {}); // Convert Map to POJO Foo anotherFoo = mapper.
Morphia is a wrapper around the Java driver for MongoDB. It acts as an ODM (Object Document Model) for MongoDB documents. Its original goal was to provide an easy mapping to POJO (Plain Old Java Objects). Nowadays, newer versions of the Java driver support this mapping out of the box.
The BSON library comprehensively supports BSON, the data storage and network transfer format that MongoDB uses for “documents”. BSON, short for Binary JSON, is a binary-encoded serialization of JSON-like documents. Documents: Documentation of the driver's support for BSON document representations.
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
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