Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversJava

Document Data Format: POJOs

On this page

  • Overview
  • Example POJO
  • Configure the Driver for POJOs
  • Summary

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

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;
}
@Override
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 or transient.

  • 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.

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, or MongoCollection instance configured to use the CodecRegistry.

  • A MongoCollection instance created with the POJO document class bound to the TDocument generic type.

Consult the following steps to see how to perform each of the configuration requirements:

  1. Configure the PojoCodecProvider. In this example, we use the automatic(true) setting of the PojoCodecProvider.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 and Convention instances that further define serialization behavior. For more information on codec providers and customization, see our guide on POJO Customization.

  2. Add the PojoCodecProvider instance to a CodecRegistry. The CodecRegistry 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 multiple CodecRegistry instances into a single one

    • getDefaultCodecRegistry() to retrieve a CodecRegistry instance from a list of codec providers

    • fromProviders() to create a CodecRegistry instance from the PojoCodecProvider

    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));
  3. Configure our MongoClient, MongoDatabase, or MongoCollection instance to use the Codecs in the CodecRegistry. You only need to configure one of these. In this example, we set the CodecRegistry on a MongoDatabase called sample_pojos using the withCodecRegistry() method.

    try (MongoClient mongoClient = MongoClients.create(uri)) {
    MongoDatabase database = mongoClient.getDatabase("sample_pojos").withCodecRegistry(pojoCodecRegistry);
    // ...
    }
  4. Pass your POJO class to your call to getCollection() as the document class parameter and specify it as the type argument of your MongoCollection 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:

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 the Codecs to any class and its properties.

  • Add the PojoCodecProvider to a CodecRegistry, and specify the registry on an instance of a MongoClient, MongoDatabase, or MongoCollection.

←  DocumentsPOJO Customization →