Docs Home → Develop Applications → MongoDB Drivers → Java
Document Data Format: POJOs
Overview
In this guide, you can learn how to store and retrieve data in the MongoDB Java driver using plain old Java objects (POJOs). POJOs are often used for data encapsulation, separating business logic from data representation.
The example in this guide shows how to perform the following:
Configure the driver to serialize and deserialize POJOs
How to read and write to documents using POJOs
Example POJO
To follow the steps in this guide, use the following sample POJO class which describes characteristics of a flower:
public class Flower { private ObjectId id; private String name; private List<String> colors; private Boolean isBlooming; private Float height; // public empty constructor needed for retrieving the POJO public Flower() {} public Flower(String name, Boolean isBlooming, Float height, List<String> colors) { this.name = name; this.isBlooming = isBlooming; this.height = height; this.colors = colors; } public ObjectId getId() { return id; } public void setId(ObjectId id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean getIsBlooming() { return isBlooming; } public void setIsBlooming(Boolean isBlooming) { this.isBlooming = isBlooming; } public Float getHeight() { return height; } public void setHeight(Float height) { this.height = height; } public List<String> getColors() { return colors; } public void setColors(List<String> colors) { this.colors = colors; } public String toString() { return "Flower [id=" + id + ", name=" + name + ", colors=" + colors + ", isBlooming=" + isBlooming + ", height=" + height + "]"; } }
If you are creating your own POJO for storing and retrieving data in MongoDB, make sure to follow these guidelines:
The POJO class should not implement interfaces or extend classes from a framework.
Include all the fields for which you want to store and retrieve data; make sure they are not
static
ortransient
.If you include public getter or setter methods using the JavaBean naming conventions in your POJO, the driver calls them when serializing or deserializing data. If you omit the getter or setter methods for a public property field, the driver accesses or assigns them directly.
Configure the Driver for POJOs
To set up the driver to store and retrieve POJOs, we need to specify:
The
PojoCodecProvider
, a codec provider that includes Codecs that define how to encode/decode the data between the POJO and MongoDB document, and which POJO classes or packages that the codecs should apply to.A
CodecRegistry
instance that contains the codecs and other related information.A
MongoClient
,MongoDatabase
, orMongoCollection
instance configured to use theCodecRegistry
.A
MongoCollection
instance created with the POJO document class bound to theTDocument
generic type.
Consult the following steps to see how to perform each of the configuration requirements:
Configure the
PojoCodecProvider
. In this example, we use theautomatic(true)
setting of thePojoCodecProvider.Builder
to apply the Codecs to any class and its properties.CodecProvider pojoCodecProvider = PojoCodecProvider.builder().automatic(true).build(); Note
Codec providers also contain other objects such as
ClassModel
andConvention
instances that further define serialization behavior. For more information on codec providers and customization, see our guide on POJO Customization.Add the
PojoCodecProvider
instance to aCodecRegistry
. TheCodecRegistry
allows you to specify one or more codec providers to encode the POJO data. In this example, we call the following methods:fromRegistries()
to combine multipleCodecRegistry
instances into a single onegetDefaultCodecRegistry()
to retrieve aCodecRegistry
instance from a list of codec providersfromProviders()
to create aCodecRegistry
instance from thePojoCodecProvider
See the following code to see how to instantiate the
CodecRegistry
:// ensure you use the following static imports before your class definition import static com.mongodb.MongoClientSettings.getDefaultCodecRegistry; import static org.bson.codecs.configuration.CodecRegistries.fromProviders; import static org.bson.codecs.configuration.CodecRegistries.fromRegistries; // ... CodecRegistry pojoCodecRegistry = fromRegistries(getDefaultCodecRegistry(), fromProviders(pojoCodecProvider)); Configure our
MongoClient
,MongoDatabase
, orMongoCollection
instance to use the Codecs in theCodecRegistry
. You only need to configure one of these. In this example, we set theCodecRegistry
on aMongoDatabase
calledsample_pojos
using thewithCodecRegistry()
method.try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("sample_pojos").withCodecRegistry(pojoCodecRegistry); // ... } Pass your POJO class to your call to
getCollection()
as the document class parameter and specify it as the type argument of yourMongoCollection
instance as follows:MongoCollection<Flower> collection = database.getCollection("flowers", Flower.class);
Once you have configured the preceding MongoCollection
instance, you
can perform the following CRUD operations
with the POJOs:
Create a document from a POJO
Retrieve data in a POJO instance
The following code snippet shows how you can insert an instance of Flower
into
the collection and then retrieve it as a List
of your POJO class objects:
Flower flower = new Flower("rose", false, 25.4f, Arrays.asList(new String[] {"red", "green"})); // insert the instance collection.insertOne(flower); // return all documents in the collection List<Flower> flowers = new ArrayList<>(); collection.find().into(flowers); System.out.println(flowers);
When you run this code, your output should look something like this:
[Flower [id=5f7f87659ed5b07cf3480a06, name=rose, colors=[green, red], isBlooming=false, height=25.4]]
Note
By default, the PojoCodecProvider
omits fields in your POJO that are
set to null
. For more information on how to specify this behavior, see
our guide on POJO Customization.
For more information about the methods and classes mentioned in this section, see the following API Documentation:
Summary
In this guide, we explained how to convert data between BSON and POJO fields by performing the following:
Instantiate a
PojoCodecProvider
which contains codecs which define how to encode/decode data between BSON and the POJO fields.Specify the automatic conversion behavior for the
PojoCodecProvider
to apply theCodecs
to any class and its properties.Add the
PojoCodecProvider
to aCodecRegistry
, and specify the registry on an instance of aMongoClient
,MongoDatabase
, orMongoCollection
.