Docs Home → Develop Applications → MongoDB Drivers → Java Sync
Document Data Format: Records
On this page
Overview
In this guide, you can learn how to store and retrieve data in the MongoDB Java Driver using Java records. Java records are a type of Java class often used to model data and separate business logic from data representation.
Tip
You can declare Java records in Java 16 or later. Learn more about the functionality and restrictions of records from Java 17 Language Updates: Record Classes.
If you are using an earlier version of Java, you can use plain old Java objects instead. See the Document Data Format: POJOs guide for implementation details.
Serialize and Deserialize a Record
The driver natively supports encoding and decoding Java records for MongoDB read and write operations using the default codec registry. The default codec registry is a collection of classes called codecs that define how to convert encode and decode Java types. Learn more about codecs and the default codec registry in the guide on Codecs.
Example Record
The code examples in this guide reference the following sample record, which describes a data storage device:
public record DataStorageRecord( String productName, double capacity ) {}
Insert a Record
You can insert a DataStorageRecord
instance as shown in the following code:
MongoCollection<DataStorageRecord> collection = database.getCollection("data_storage_devices", DataStorageRecord.class); // insert the record collection.insertOne(new DataStorageRecord("2TB SSD", 1.71));
Retrieve a Record
You can retrieve documents as DataStorageRecord
instances and print them
as shown in the following code:
MongoCollection<DataStorageRecord> collection = database.getCollection("data_storage_devices", DataStorageRecord.class); // retrieve and print the records List<DataStorageRecord> records = new ArrayList<DataStorageRecord>(); collection.find().into(records); records.forEach(System.out::println);
DataStorageRecord[productName=1TB SSD, capacity=1.71]