The BSON library for MongoDB Java Driver - A high-performance binary serialization format and library for MongoDB documents
—
The legacy BSON API provides backward compatibility with the original MongoDB Java driver interfaces. This API is maintained for existing applications and offers a familiar Map-like interface for working with BSON documents, along with traditional encoding/decoding operations.
The BSONObject interface represents the core abstraction for BSON documents in the legacy API.
public interface BSONObject {
/**
* Sets a name/value pair in this object.
* @param key name of the field
* @param v value of the field
* @return the old value for the field, or null if none existed
*/
Object put(String key, Object v);
/**
* Sets all key/value pairs from a map into this object.
* @param m the map of key/value pairs
*/
void putAll(Map<String, ? extends Object> m);
/**
* Gets a field from this object by a given name.
* @param key the name of the field to fetch
* @return the field, if found
*/
Object get(String key);
/**
* Returns a map representing this BSONObject.
* @return the map
*/
Map toMap();
/**
* Removes a field with a given name from this object.
* @param key the name of the field to remove
* @return the object removed
*/
Object removeField(String key);
/**
* Checks if this object contains a field with the given name.
* @param s field name for which to check
* @return true if the field name exists
*/
boolean containsField(String s);
/**
* Returns this object's fields' names.
* @return set of field names
*/
Set<String> keySet();
/**
* Marks this object as partial.
* @param b whether or not this object is partial
*/
void markAsPartialObject(boolean b);
/**
* Whether or not this object has been marked as partial.
* @return true if this object is partial
*/
boolean isPartialObject();
}The BasicBSONObject class is the primary implementation of BSONObject.
public class BasicBSONObject implements BSONObject, Map<String, Object>, Serializable {
/**
* Creates an empty object.
*/
public BasicBSONObject();
/**
* Creates a BasicBSONObject from a map of key-value pairs.
* @param m map of key-value pairs
*/
public BasicBSONObject(Map<String, Object> m);
/**
* Creates an object with the given key/value.
* @param key key under which to store
* @param value value to store
*/
public BasicBSONObject(String key, Object value);
/**
* Creates an object from a string representation.
* @param s the string representation
* @return the BasicBSONObject
*/
public static BasicBSONObject parse(String s);
// BSONObject implementation
public Object put(String key, Object v);
public void putAll(Map<String, ? extends Object> m);
public Object get(String key);
public Map toMap();
public Object removeField(String key);
public boolean containsField(String s);
public Set<String> keySet();
public void markAsPartialObject(boolean b);
public boolean isPartialObject();
// Map interface implementation
public int size();
public boolean isEmpty();
public boolean containsValue(Object value);
public Object remove(Object key);
public void clear();
public Collection<Object> values();
public Set<Map.Entry<String, Object>> entrySet();
/**
* Returns a JSON representation of this object.
* @return the JSON string
*/
public String toJson();
/**
* Appends a key/value pair to this object.
* @param key the name of the field
* @param val the value of the field
* @return this object
*/
public BasicBSONObject append(String key, Object val);
/**
* Gets a value by key and casts it to the specified type.
* @param key the key
* @param clazz the class to cast to
* @param <T> the type
* @return the value cast to type T
*/
public <T> T get(String key, Class<T> clazz);
/**
* Gets a value by key as a String.
* @param key the key
* @return the value as a String
*/
public String getString(String key);
/**
* Gets a value by key as a String, with a default value.
* @param key the key
* @param def the default value
* @return the value as a String, or the default if not found
*/
public String getString(String key, String def);
/**
* Gets a value by key as an int.
* @param key the key
* @return the value as an int
*/
public int getInt(String key);
/**
* Gets a value by key as an int, with a default value.
* @param key the key
* @param def the default value
* @return the value as an int, or the default if not found
*/
public int getInt(String key, int def);
/**
* Gets a value by key as a long.
* @param key the key
* @return the value as a long
*/
public long getLong(String key);
/**
* Gets a value by key as a long, with a default value.
* @param key the key
* @param def the default value
* @return the value as a long, or the default if not found
*/
public long getLong(String key, long def);
/**
* Gets a value by key as a double.
* @param key the key
* @return the value as a double
*/
public double getDouble(String key);
/**
* Gets a value by key as a double, with a default value.
* @param key the key
* @param def the default value
* @return the value as a double, or the default if not found
*/
public double getDouble(String key, double def);
/**
* Gets a value by key as a boolean.
* @param key the key
* @return the value as a boolean
*/
public boolean getBoolean(String key);
/**
* Gets a value by key as a boolean, with a default value.
* @param key the key
* @param def the default value
* @return the value as a boolean, or the default if not found
*/
public boolean getBoolean(String key, boolean def);
/**
* Gets a value by key as an ObjectId.
* @param key the key
* @return the value as an ObjectId
*/
public ObjectId getObjectId(String key);
/**
* Gets a value by key as an ObjectId, with a default value.
* @param key the key
* @param def the default value
* @return the value as an ObjectId, or the default if not found
*/
public ObjectId getObjectId(String key, ObjectId def);
/**
* Gets a value by key as a Date.
* @param key the key
* @return the value as a Date
*/
public Date getDate(String key);
/**
* Gets a value by key as a Date, with a default value.
* @param key the key
* @param def the default value
* @return the value as a Date, or the default if not found
*/
public Date getDate(String key, Date def);
public boolean equals(Object o);
public int hashCode();
public String toString();
}The BasicBSONList class represents a BSON array in the legacy API.
public class BasicBSONList extends ArrayList<Object> implements BSONObject {
/**
* Creates an empty BasicBSONList.
*/
public BasicBSONList();
/**
* Puts a value at the given index.
* @param key the index as a string
* @param v the value
* @return the previous value at that index
*/
public Object put(String key, Object v);
/**
* Puts a value at the given numeric index.
* @param i the index
* @param v the value
* @return the previous value at that index
*/
public Object put(int i, Object v);
/**
* Gets a value by string index.
* @param key the index as a string
* @return the value at that index
*/
public Object get(String key);
/**
* Removes a field by string index.
* @param key the index as a string
* @return the removed value
*/
public Object removeField(String key);
/**
* Checks if a field exists by string index.
* @param s the index as a string
* @return true if the field exists
*/
public boolean containsField(String s);
/**
* Gets all string indices as a set.
* @return set of string indices
*/
public Set<String> keySet();
public void putAll(Map<String, ? extends Object> m);
public Map<String, Object> toMap();
public void markAsPartialObject(boolean b);
public boolean isPartialObject();
}public interface BSONEncoder {
/**
* Encodes a BSONObject.
* @param o the BSONObject to encode
* @return the encoded bytes
*/
byte[] encode(BSONObject o);
/**
* Encodes a BSONObject and writes to the provided output stream.
* @param o the BSONObject to encode
* @param buf the output buffer
* @return the number of bytes written
*/
int encode(BSONObject o, OutputBuffer buf);
/**
* Sets the encoder factory.
* @param factory the encoder factory
*/
void set(BSONEncoderFactory factory);
}public interface BSONDecoder {
/**
* Decodes a BSON byte array into a BSONObject.
* @param b the byte array
* @return the decoded BSONObject
*/
BSONObject decode(byte[] b);
/**
* Decodes BSON data from an input stream.
* @param in the input stream
* @return the decoded BSONObject
*/
BSONObject decode(InputStream in);
/**
* Reads a single BSON object from the input stream.
* @param in the input stream
* @param collection the collection name (may be null)
* @return the decoded BSONObject
*/
BSONObject readObject(InputStream in, String collection);
/**
* Reads a single BSON object from a byte buffer.
* @param buf the byte buffer
* @return the decoded BSONObject
*/
BSONObject readObject(ByteBuffer buf);
/**
* Gets the decoder factory.
* @return the decoder factory
*/
BSONDecoderFactory getDBDecoderFactory();
/**
* Sets the decoder factory.
* @param factory the decoder factory
*/
void setDBDecoderFactory(BSONDecoderFactory factory);
}public class BasicBSONEncoder implements BSONEncoder {
/**
* Creates a new BasicBSONEncoder.
*/
public BasicBSONEncoder();
public byte[] encode(BSONObject o);
public int encode(BSONObject o, OutputBuffer buf);
public void set(BSONEncoderFactory factory);
/**
* Encodes a BSONObject and returns the encoded length.
* @param o the BSONObject to encode
* @param buf the output buffer
* @return the encoded length
*/
protected int putObject(BSONObject o, OutputBuffer buf);
/**
* Encodes a string.
* @param s the string
* @param buf the output buffer
*/
protected void putString(String s, OutputBuffer buf);
/**
* Encodes a string with null termination.
* @param s the string
* @param buf the output buffer
*/
protected void putCString(String s, OutputBuffer buf);
}public class BasicBSONDecoder implements BSONDecoder {
/**
* Creates a new BasicBSONDecoder.
*/
public BasicBSONDecoder();
public BSONObject decode(byte[] b);
public BSONObject decode(InputStream in);
public BSONObject readObject(InputStream in, String collection);
public BSONObject readObject(ByteBuffer buf);
public BSONDecoderFactory getDBDecoderFactory();
public void setDBDecoderFactory(BSONDecoderFactory factory);
/**
* Reads an object from the byte buffer.
* @param buf the byte buffer
* @param callback the callback for handling the object
* @return the number of bytes read
*/
public int decode(ByteBuffer buf, BSONCallback callback);
/**
* Reads a string from the buffer.
* @param buf the byte buffer
* @param stringCodec the string codec to use
* @return the decoded string
*/
protected String readString(ByteBuffer buf, StringCodec stringCodec);
/**
* Reads a C-style null-terminated string.
* @param buf the byte buffer
* @param stringCodec the string codec to use
* @return the decoded string
*/
protected String readCString(ByteBuffer buf, StringCodec stringCodec);
}public interface BSONCallback {
/**
* Called when the start of a BSON object is encountered.
* @return the object created for this BSON object
*/
BSONObject objectStart();
/**
* Called when the start of a BSON object is encountered with a name.
* @param name the name of the object
* @param embedded true if this is an embedded object
* @return the object created for this BSON object
*/
BSONObject objectStart(String name, boolean embedded);
/**
* Called when the end of a BSON object is encountered.
* @param o the BSON object that is ending
* @return the finished object
*/
Object objectDone(BSONObject o);
/**
* Called when the start of a BSON array is encountered.
* @return the array object
*/
BSONObject arrayStart();
/**
* Called when the start of a BSON array is encountered with a name.
* @param name the name of the array
* @return the array object
*/
BSONObject arrayStart(String name);
/**
* Called when the end of a BSON array is encountered.
* @param array the array that is ending
* @return the finished array
*/
Object arrayDone(BSONObject array);
/**
* Called when a field is encountered.
* @param o the containing object
* @param name the field name
* @param value the field value
* @throws BSONException if an error occurs
*/
void gotNull(String name);
void gotBoolean(String name, boolean value);
void gotDouble(String name, double value);
void gotInt(String name, int value);
void gotLong(String name, long value);
void gotDate(String name, long millis);
void gotString(String name, String value);
void gotSymbol(String name, String value);
void gotRegex(String name, String pattern, String flags);
void gotTimestamp(String name, int time, int increment);
void gotObjectId(String name, ObjectId id);
void gotDBRef(String name, String namespace, ObjectId id);
void gotBinaryArray(String name, byte[] data);
void gotBinary(String name, byte type, byte[] data);
void gotUUID(String name, long part1, long part2);
void gotCode(String name, String code);
void gotCodeWScope(String name, String code, Object scope);
/**
* Resets the callback.
*/
void reset();
/**
* Gets the root object.
* @return the root object
*/
Object get();
/**
* Creates a BSON object.
* @param embedded true if this is an embedded object
* @param path the path to this object
* @return the BSON object
*/
BSONObject create(boolean embedded, String path);
/**
* Creates a BSON list.
* @param path the path to this list
* @return the BSON list
*/
BSONObject createList(String path);
}public class BasicBSONCallback implements BSONCallback {
/**
* Creates a new BasicBSONCallback.
*/
public BasicBSONCallback();
// BSONCallback implementation
public BSONObject objectStart();
public BSONObject objectStart(String name, boolean embedded);
public Object objectDone(BSONObject o);
public BSONObject arrayStart();
public BSONObject arrayStart(String name);
public Object arrayDone(BSONObject array);
public void gotNull(String name);
public void gotBoolean(String name, boolean value);
public void gotDouble(String name, double value);
public void gotInt(String name, int value);
public void gotLong(String name, long value);
public void gotDate(String name, long millis);
public void gotString(String name, String value);
public void gotSymbol(String name, String value);
public void gotRegex(String name, String pattern, String flags);
public void gotTimestamp(String name, int time, int increment);
public void gotObjectId(String name, ObjectId id);
public void gotDBRef(String name, String namespace, ObjectId id);
public void gotBinaryArray(String name, byte[] data);
public void gotBinary(String name, byte type, byte[] data);
public void gotUUID(String name, long part1, long part2);
public void gotCode(String name, String code);
public void gotCodeWScope(String name, String code, Object scope);
public void reset();
public Object get();
public BSONObject create(boolean embedded, String path);
public BSONObject createList(String path);
/**
* Creates a BSON object for the given path.
* @param embedded true if this is an embedded object
* @param path the path
* @return the BSON object
*/
public BSONObject createObject(String path);
/**
* Gets the current object being processed.
* @return the current object
*/
public BSONObject getCurrent();
/**
* Gets the current field name being processed.
* @return the current field name
*/
public String getCurName();
/**
* Sets a field in the current object.
* @param name the field name
* @param value the field value
*/
public void setCurrentObject(String name, Object value);
}public final class BSON {
/**
* Regular expression type.
*/
public static final byte REGEX = 11;
/**
* Array type.
*/
public static final byte ARRAY = 4;
/**
* Object type.
*/
public static final byte OBJECT = 3;
/**
* Encodes a BSONObject to bytes.
* @param obj the BSONObject to encode
* @return the encoded bytes
*/
public static byte[] encode(BSONObject obj);
/**
* Decodes bytes to a BSONObject.
* @param bytes the bytes to decode
* @return the decoded BSONObject
*/
public static BSONObject decode(byte[] bytes);
/**
* Adds an encoding hook.
* @param clazz the class to add the hook for
* @param transformer the transformer
*/
public static void addEncodingHook(Class clazz, Transformer transformer);
/**
* Adds a decoding hook.
* @param clazz the class to add the hook for
* @param transformer the transformer
*/
public static void addDecodingHook(Class clazz, Transformer transformer);
/**
* Removes encoding hooks for the given class.
* @param clazz the class
*/
public static void removeEncodingHooks(Class clazz);
/**
* Removes decoding hooks for the given class.
* @param clazz the class
*/
public static void removeDecodingHooks(Class clazz);
/**
* Gets the encoding hooks for the given class.
* @param clazz the class
* @return list of transformers
*/
public static List<Transformer> getEncodingHooks(Class clazz);
/**
* Gets the decoding hooks for the given class.
* @param clazz the class
* @return list of transformers
*/
public static List<Transformer> getDecodingHooks(Class clazz);
/**
* Clears all encoding and decoding hooks.
*/
public static void clearAllHooks();
}import org.bson.*;
import org.bson.types.ObjectId;
// Create a BasicBSONObject
BasicBSONObject person = new BasicBSONObject();
person.put("_id", new ObjectId());
person.put("name", "John Doe");
person.put("age", 30);
person.put("active", true);
// Chain operations
BasicBSONObject address = new BasicBSONObject("street", "123 Main St")
.append("city", "Anytown")
.append("zip", "12345");
person.put("address", address);
// Type-safe getters
String name = person.getString("name");
int age = person.getInt("age");
boolean active = person.getBoolean("active");
ObjectId id = person.getObjectId("_id");
// Convert to JSON
String json = person.toJson();// Create a BasicBSONList
BasicBSONList skills = new BasicBSONList();
skills.add("Java");
skills.add("MongoDB");
skills.add("BSON");
// Add to document
BasicBSONObject developer = new BasicBSONObject("name", "Alice")
.append("skills", skills);
// Access array elements
String firstSkill = (String) skills.get(0);
int skillCount = skills.size();
// Iterate over array
for (Object skill : skills) {
System.out.println(skill);
}import org.bson.*;
// Create a document
BasicBSONObject document = new BasicBSONObject("message", "Hello BSON")
.append("timestamp", System.currentTimeMillis())
.append("version", 1);
// Encode to bytes
BasicBSONEncoder encoder = new BasicBSONEncoder();
byte[] encodedData = encoder.encode(document);
// Decode from bytes
BasicBSONDecoder decoder = new BasicBSONDecoder();
BSONObject decodedDocument = decoder.decode(encodedData);
// Verify data
String message = (String) decodedDocument.get("message");
Long timestamp = (Long) decodedDocument.get("timestamp");import org.bson.*;
// Custom callback for processing specific fields
class CustomBSONCallback extends BasicBSONCallback {
@Override
public void gotString(String name, String value) {
if ("email".equals(name)) {
// Validate email format
if (!value.contains("@")) {
throw new BSONException("Invalid email format: " + value);
}
}
super.gotString(name, value);
}
@Override
public void gotInt(String name, int value) {
if ("age".equals(name) && value < 0) {
throw new BSONException("Age cannot be negative: " + value);
}
super.gotInt(name, value);
}
}
// Use custom callback
BasicBSONDecoder decoder = new BasicBSONDecoder();
CustomBSONCallback callback = new CustomBSONCallback();
decoder.decode(bsonData, callback);
BSONObject validatedObject = (BSONObject) callback.get();// Legacy API
BasicBSONObject legacyDoc = new BasicBSONObject("name", "example")
.append("value", 42);
// Convert to modern API
Document modernDoc = new Document(legacyDoc.toMap());
// Or create BsonDocument
BsonDocument bsonDoc = new BsonDocument();
for (String key : legacyDoc.keySet()) {
Object value = legacyDoc.get(key);
if (value instanceof String) {
bsonDoc.put(key, new BsonString((String) value));
} else if (value instanceof Integer) {
bsonDoc.put(key, new BsonInt32((Integer) value));
}
// Handle other types as needed
}// Create nested structure
BasicBSONObject user = new BasicBSONObject();
user.put("_id", new ObjectId());
user.put("username", "johndoe");
BasicBSONObject profile = new BasicBSONObject();
profile.put("firstName", "John");
profile.put("lastName", "Doe");
profile.put("email", "john@example.com");
BasicBSONObject preferences = new BasicBSONObject();
preferences.put("theme", "dark");
preferences.put("notifications", true);
profile.put("preferences", preferences);
user.put("profile", profile);
// Access nested values
BasicBSONObject userProfile = (BasicBSONObject) user.get("profile");
String firstName = userProfile.getString("firstName");
BasicBSONObject userPrefs = (BasicBSONObject) userProfile.get("preferences");
String theme = userPrefs.getString("theme");Install with Tessl CLI
npx tessl i tessl/maven-org-mongodb--bson