The BSON library for MongoDB Java Driver - A high-performance binary serialization format and library for MongoDB documents
—
The BSON I/O system provides high-performance binary reading and writing capabilities for BSON data. It includes abstract reader/writer interfaces, concrete implementations for different data sources, and buffering support for optimal performance.
The BsonReader interface provides the core interface for reading BSON data.
public interface BsonReader extends Closeable {
/**
* Reads a BSON type from the reader.
* @return the BSON type
*/
BsonType readBsonType();
/**
* Reads the name of an element from the reader.
* @return the element name
*/
String readName();
/**
* Reads a BSON Binary value from the reader.
* @return the Binary value
*/
BsonBinary readBinaryData();
/**
* Reads a BSON Boolean value from the reader.
* @return the Boolean value
*/
boolean readBoolean();
/**
* Reads a BSON DateTime value from the reader.
* @return the DateTime value as milliseconds since epoch
*/
long readDateTime();
/**
* Reads a BSON Double value from the reader.
* @return the Double value
*/
double readDouble();
/**
* Reads a BSON Int32 value from the reader.
* @return the Int32 value
*/
int readInt32();
/**
* Reads a BSON Int64 value from the reader.
* @return the Int64 value
*/
long readInt64();
/**
* Reads a BSON Decimal128 value from the reader.
* @return the Decimal128 value
*/
Decimal128 readDecimal128();
/**
* Reads a BSON JavaScript value from the reader.
* @return the JavaScript code
*/
String readJavaScript();
/**
* Reads a BSON JavaScript with Scope value from the reader.
* @return the JavaScript code
*/
String readJavaScriptWithScope();
/**
* Reads a BSON MaxKey value from the reader.
*/
void readMaxKey();
/**
* Reads a BSON MinKey value from the reader.
*/
void readMinKey();
/**
* Reads a BSON null value from the reader.
*/
void readNull();
/**
* Reads a BSON ObjectId value from the reader.
* @return the ObjectId value
*/
ObjectId readObjectId();
/**
* Reads a BSON regular expression value from the reader.
* @return the regular expression
*/
BsonRegularExpression readRegularExpression();
/**
* Reads a BSON string value from the reader.
* @return the string value
*/
String readString();
/**
* Reads a BSON symbol value from the reader.
* @return the symbol value
*/
String readSymbol();
/**
* Reads a BSON timestamp value from the reader.
* @return the timestamp
*/
BsonTimestamp readTimestamp();
/**
* Reads a BSON undefined value from the reader.
*/
void readUndefined();
/**
* Reads the start of a BSON array.
*/
void readStartArray();
/**
* Reads the end of a BSON array.
*/
void readEndArray();
/**
* Reads the start of a BSON document.
*/
void readStartDocument();
/**
* Reads the end of a BSON document.
*/
void readEndDocument();
/**
* Returns a mark for the current position.
* @return the mark
*/
BsonReaderMark getMark();
/**
* Resets the reader to the marked position.
* @param mark the mark to reset to
*/
void reset(BsonReaderMark mark);
/**
* Gets the current context type.
* @return the current context type
*/
public BsonContextType getCurrentBsonType();
/**
* Gets the current name.
* @return the current name
*/
public String getCurrentName();
/**
* Gets the reader state.
* @return the reader state
*/
public AbstractBsonReader.State getState();
/**
* Skips the name (reader must be positioned on a name).
*/
void skipName();
/**
* Skips the value (reader must be positioned on a value).
*/
void skipValue();
void close();
}The abstract BsonWriter class provides the core interface for writing BSON data.
class BsonWriter implements Closeable, Flushable {
/**
* Writes a BSON Binary value to the writer.
* @param binary the Binary value
*/
void writeBinaryData(BsonBinary binary);
/**
* Writes a BSON Binary value to the writer.
* @param name the field name
* @param binary the Binary value
*/
public void writeBinaryData(String name, BsonBinary binary);
/**
* Writes a BSON Boolean value to the writer.
* @param value the Boolean value
*/
void writeBoolean(boolean value);
/**
* Writes a BSON Boolean value to the writer.
* @param name the field name
* @param value the Boolean value
*/
public void writeBoolean(String name, boolean value);
/**
* Writes a BSON DateTime value to the writer.
* @param value the DateTime value as milliseconds since epoch
*/
void writeDateTime(long value);
/**
* Writes a BSON DateTime value to the writer.
* @param name the field name
* @param value the DateTime value as milliseconds since epoch
*/
public void writeDateTime(String name, long value);
/**
* Writes a BSON Double value to the writer.
* @param value the Double value
*/
void writeDouble(double value);
/**
* Writes a BSON Double value to the writer.
* @param name the field name
* @param value the Double value
*/
public void writeDouble(String name, double value);
/**
* Writes a BSON Int32 value to the writer.
* @param value the Int32 value
*/
void writeInt32(int value);
/**
* Writes a BSON Int32 value to the writer.
* @param name the field name
* @param value the Int32 value
*/
public void writeInt32(String name, int value);
/**
* Writes a BSON Int64 value to the writer.
* @param value the Int64 value
*/
void writeInt64(long value);
/**
* Writes a BSON Int64 value to the writer.
* @param name the field name
* @param value the Int64 value
*/
public void writeInt64(String name, long value);
/**
* Writes a BSON Decimal128 value to the writer.
* @param value the Decimal128 value
*/
void writeDecimal128(Decimal128 value);
/**
* Writes a BSON JavaScript value to the writer.
* @param code the JavaScript code
*/
void writeJavaScript(String code);
/**
* Writes a BSON JavaScript with Scope value to the writer.
* @param code the JavaScript code
*/
void writeJavaScriptWithScope(String code);
/**
* Writes a BSON MaxKey value to the writer.
*/
void writeMaxKey();
/**
* Writes a BSON MinKey value to the writer.
*/
void writeMinKey();
/**
* Writes a field name to the writer.
* @param name the field name
*/
void writeName(String name);
/**
* Writes a BSON null value to the writer.
*/
void writeNull();
/**
* Writes a BSON null value to the writer.
* @param name the field name
*/
public void writeNull(String name);
/**
* Writes a BSON ObjectId value to the writer.
* @param objectId the ObjectId value
*/
void writeObjectId(ObjectId objectId);
/**
* Writes a BSON regular expression value to the writer.
* @param regularExpression the regular expression
*/
void writeRegularExpression(BsonRegularExpression regularExpression);
/**
* Writes a BSON string value to the writer.
* @param value the string value
*/
void writeString(String value);
/**
* Writes a BSON string value to the writer.
* @param name the field name
* @param value the string value
*/
public void writeString(String name, String value);
/**
* Writes a BSON symbol value to the writer.
* @param value the symbol value
*/
void writeSymbol(String value);
/**
* Writes a BSON timestamp value to the writer.
* @param value the timestamp
*/
void writeTimestamp(BsonTimestamp value);
/**
* Writes a BSON undefined value to the writer.
*/
void writeUndefined();
/**
* Writes the start of a BSON array to the writer.
*/
void writeStartArray();
/**
* Writes the start of a BSON array to the writer.
* @param name the field name
*/
public void writeStartArray(String name);
/**
* Writes the end of a BSON array to the writer.
*/
void writeEndArray();
/**
* Writes the start of a BSON document to the writer.
*/
void writeStartDocument();
/**
* Writes the start of a BSON document to the writer.
* @param name the field name
*/
public void writeStartDocument(String name);
/**
* Writes the end of a BSON document to the writer.
*/
void writeEndDocument();
/**
* Gets the writer settings.
* @return the writer settings
*/
public BsonWriterSettings getSettings();
/**
* Returns true if the writer is closed.
* @return true if closed
*/
public boolean isClosed();
/**
* Flushes any pending output to the underlying stream.
*/
void flush();
void close();
}public class BsonBinaryReader extends AbstractBsonReader {
/**
* Constructs a new instance.
* @param byteBuffer the input buffer, which must be positioned at the first byte of a BSON document
*/
public BsonBinaryReader(ByteBuffer byteBuffer);
/**
* Constructs a new instance.
* @param bsonInput the input stream
*/
public BsonBinaryReader(BsonInput bsonInput);
/**
* Gets the mark.
* @return the mark
*/
public BsonReaderMark getMark();
/**
* Resets the reader to the given mark.
* @param mark the mark to reset to
*/
public void reset(BsonReaderMark mark);
/**
* Gets the number of bytes read from the underlying stream.
* @return the number of bytes read
*/
public int getBytesRead();
// Implementation of abstract methods from BsonReader
public BsonType readBsonType();
public String readName();
public void skipName();
public void skipValue();
// ... all other BsonReader methods
}public class BsonBinaryWriter extends AbstractBsonWriter {
/**
* Constructs a new instance.
* @param bsonOutput the output stream
*/
public BsonBinaryWriter(BsonOutput bsonOutput);
/**
* Constructs a new instance.
* @param bsonOutput the output stream
* @param settings the writer settings
*/
public BsonBinaryWriter(BsonOutput bsonOutput, BsonBinaryWriterSettings settings);
/**
* Gets the number of bytes written to the underlying stream.
* @return the number of bytes written
*/
public int getBytesWritten();
// Implementation of abstract methods from BsonWriter
public void writeBinaryData(BsonBinary binary);
public void writeBoolean(boolean value);
public void writeDateTime(long value);
public void writeDouble(double value);
public void writeInt32(int value);
public void writeInt64(long value);
// ... all other BsonWriter methods
}public class BsonDocumentReader extends AbstractBsonReader {
/**
* Constructs a new instance.
* @param document the document to read from
*/
public BsonDocumentReader(BsonDocument document);
// Implementation of BsonReader interface
public BsonType readBsonType();
public void readStartDocument();
public void readEndDocument();
public void readStartArray();
public void readEndArray();
// ... other methods
}
public class BsonDocumentWriter extends AbstractBsonWriter {
/**
* Constructs a new instance.
* @param document the document to write to
*/
public BsonDocumentWriter(BsonDocument document);
/**
* Gets the document being written to.
* @return the document
*/
public BsonDocument getDocument();
// Implementation of BsonWriter interface
public void writeBinaryData(BsonBinary binary);
public void writeBoolean(boolean value);
// ... other methods
}The ByteBuf interface provides an abstraction for binary data buffers with reference counting.
public interface ByteBuf extends ReferenceCounted {
/**
* Gets the capacity of this buffer.
* @return the capacity
*/
int capacity();
/**
* Gets a byte at the given index.
* @param index the index
* @return the byte at the given index
*/
byte get(int index);
/**
* Gets bytes from the given index.
* @param index the index to start at
* @param bytes the byte array to copy into
* @return this
*/
ByteBuf get(int index, byte[] bytes);
/**
* Gets bytes from the given index.
* @param index the index to start at
* @param bytes the byte array to copy into
* @param offset the offset into the byte array
* @param length the number of bytes to copy
* @return this
*/
ByteBuf get(int index, byte[] bytes, int offset, int length);
/**
* Gets a little-endian 32-bit integer at the given index.
* @param index the index
* @return the 32-bit integer
*/
int getInt(int index);
/**
* Gets a little-endian 64-bit integer at the given index.
* @param index the index
* @return the 64-bit integer
*/
long getLong(int index);
/**
* Gets a little-endian 64-bit double at the given index.
* @param index the index
* @return the 64-bit double
*/
double getDouble(int index);
/**
* Puts a byte at the given index.
* @param index the index
* @param b the byte
* @return this
*/
ByteBuf put(int index, byte b);
/**
* Puts bytes at the given index.
* @param index the index
* @param src the source byte array
* @return this
*/
ByteBuf put(int index, byte[] src);
/**
* Puts a little-endian 32-bit integer at the given index.
* @param index the index
* @param value the 32-bit integer value
* @return this
*/
ByteBuf putInt(int index, int value);
/**
* Puts a little-endian 64-bit integer at the given index.
* @param index the index
* @param value the 64-bit integer value
* @return this
*/
ByteBuf putLong(int index, long value);
/**
* Puts a little-endian 64-bit double at the given index.
* @param index the index
* @param value the 64-bit double value
* @return this
*/
ByteBuf putDouble(int index, double value);
/**
* Returns a slice of this buffer.
* @param index the starting index of the slice
* @param length the length of the slice
* @return the sliced buffer
*/
ByteBuf slice(int index, int length);
/**
* Returns a duplicate of this buffer.
* @return the duplicated buffer
*/
ByteBuf duplicate();
/**
* Converts this buffer to a byte array.
* @return the byte array
*/
byte[] array();
/**
* Gets the reference count.
* @return the reference count
*/
int getReferenceCount();
/**
* Retain an additional reference to this buffer.
* @return this
*/
ByteBuf retain();
/**
* Release a reference to this buffer.
* @return this
*/
ByteBuf release();
}public final class BsonBinaryWriterSettings {
/**
* Gets the maximum size for a BSON document.
* @return the maximum document size
*/
public int getMaxDocumentSize();
/**
* Creates a builder for BsonBinaryWriterSettings.
* @return the builder
*/
public static Builder builder();
public static final class Builder {
/**
* Sets the maximum document size.
* @param maxDocumentSize the maximum document size
* @return this
*/
public Builder maxDocumentSize(int maxDocumentSize);
/**
* Build the settings.
* @return the settings
*/
public BsonBinaryWriterSettings build();
}
}
public class BsonWriterSettings {
/**
* Gets whether output should be indented.
* @return true if output should be indented
*/
public boolean isIndent();
/**
* Gets the indent characters.
* @return the indent characters
*/
public String getIndentCharacters();
/**
* Gets the new line characters.
* @return the new line characters
*/
public String getNewLineCharacters();
/**
* Creates a builder for BsonWriterSettings.
* @return the builder
*/
public static Builder builder();
public static final class Builder {
/**
* Sets whether the output should be indented.
* @param indent true if output should be indented
* @return this
*/
public Builder indent(boolean indent);
/**
* Sets the indent characters.
* @param indentCharacters the indent characters
* @return this
*/
public Builder indentCharacters(String indentCharacters);
/**
* Sets the new line characters.
* @param newLineCharacters the new line characters
* @return this
*/
public Builder newLineCharacters(String newLineCharacters);
/**
* Build the settings.
* @return the settings
*/
public BsonWriterSettings build();
}
}import org.bson.*;
import org.bson.io.*;
import java.nio.ByteBuffer;
// Write BSON data to a buffer
BasicOutputBuffer outputBuffer = new BasicOutputBuffer();
BsonBinaryWriter writer = new BsonBinaryWriter(outputBuffer);
writer.writeStartDocument();
writer.writeString("name", "John Doe");
writer.writeInt32("age", 30);
writer.writeBoolean("active", true);
writer.writeEndDocument();
writer.close();
// Read BSON data from buffer
byte[] bytes = outputBuffer.toByteArray();
BsonBinaryReader reader = new BsonBinaryReader(ByteBuffer.wrap(bytes));
reader.readStartDocument();
while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {
String fieldName = reader.readName();
switch (reader.getCurrentBsonType()) {
case STRING:
String stringValue = reader.readString();
break;
case INT32:
int intValue = reader.readInt32();
break;
case BOOLEAN:
boolean boolValue = reader.readBoolean();
break;
}
}
reader.readEndDocument();
reader.close();import org.bson.*;
// Write to a BsonDocument using BsonDocumentWriter
BsonDocument document = new BsonDocument();
BsonDocumentWriter docWriter = new BsonDocumentWriter(document);
docWriter.writeStartDocument();
docWriter.writeString("title", "BSON Example");
docWriter.writeStartArray("tags");
docWriter.writeString("mongodb");
docWriter.writeString("bson");
docWriter.writeEndArray();
docWriter.writeEndDocument();
docWriter.close();
// Read from a BsonDocument using BsonDocumentReader
BsonDocumentReader docReader = new BsonDocumentReader(document);
docReader.readStartDocument();
while (docReader.readBsonType() != BsonType.END_OF_DOCUMENT) {
String name = docReader.readName();
if (name.equals("title")) {
String title = docReader.readString();
} else if (name.equals("tags")) {
docReader.readStartArray();
while (docReader.readBsonType() != BsonType.END_OF_DOCUMENT) {
String tag = docReader.readString();
}
docReader.readEndArray();
}
}
docReader.readEndDocument();
docReader.close();import org.bson.*;
import org.bson.io.*;
import java.io.*;
// Stream writing for large documents
try (FileOutputStream fos = new FileOutputStream("large-document.bson");
BsonBinaryWriter writer = new BsonBinaryWriter(new BasicOutputBuffer(fos))) {
writer.writeStartDocument();
writer.writeStartArray("items");
for (int i = 0; i < 1000000; i++) {
writer.writeStartDocument();
writer.writeInt32("id", i);
writer.writeString("name", "Item " + i);
writer.writeEndDocument();
}
writer.writeEndArray();
writer.writeEndDocument();
}
// Stream reading for large documents
try (FileInputStream fis = new FileInputStream("large-document.bson");
BsonBinaryReader reader = new BsonBinaryReader(ByteBuffer.wrap(fis.readAllBytes()))) {
reader.readStartDocument();
reader.readName(); // "items"
reader.readStartArray();
while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {
reader.readStartDocument();
reader.readName(); // "id"
int id = reader.readInt32();
reader.readName(); // "name"
String name = reader.readString();
reader.readEndDocument();
// Process item...
}
reader.readEndArray();
reader.readEndDocument();
}BsonBinaryReader reader = new BsonBinaryReader(byteBuffer);
reader.readStartDocument();
BsonReaderMark mark = reader.getMark(); // Mark current position
reader.readName(); // Read first field
String firstField = reader.readString();
reader.reset(mark); // Reset to marked position
reader.readName(); // Read first field again
String sameField = reader.readString(); // Same value as firstFieldInstall with Tessl CLI
npx tessl i tessl/maven-org-mongodb--bson