or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

aggregation.mdauthentication-security.mdbson-types.mdchange-streams.mdcollection-operations.mdconfiguration.mdconnection-management.mddatabase-operations.mdgridfs.mdindex.mdquery-building.mdsessions-transactions.md

bson-types.mddocs/

0

# BSON Data Types

1

2

Comprehensive BSON document and type system providing both flexible document APIs and strongly-typed value representations for MongoDB data interchange.

3

4

## Capabilities

5

6

### Document Class

7

8

Flexible document representation extending LinkedHashMap for easy MongoDB document manipulation.

9

10

```java { .api }

11

/**

12

* BSON document representation extending Map<String, Object>

13

*/

14

public class Document extends LinkedHashMap<String, Object> {

15

// Constructors

16

public Document();

17

public Document(String key, Object value);

18

public Document(Map<String, Object> map);

19

20

// Fluent building

21

public Document append(String key, Object value);

22

23

// JSON conversion

24

public String toJson();

25

public String toJson(JsonWriterSettings settings);

26

public static Document parse(String json);

27

public static Document parse(String json, Codec<Document> codec);

28

29

// Type-safe field access

30

public Object get(Object key);

31

public <T> T get(Object key, Class<T> clazz);

32

public String getString(Object key);

33

public Integer getInteger(Object key);

34

public Long getLong(Object key);

35

public Double getDouble(Object key);

36

public Boolean getBoolean(Object key);

37

public Date getDate(Object key);

38

public ObjectId getObjectId(Object key);

39

public List<Object> getList(Object key, Class<?> clazz);

40

}

41

```

42

43

**Document Usage Examples:**

44

45

```java

46

// Create document

47

Document user = new Document("name", "Alice")

48

.append("age", 30)

49

.append("email", "alice@example.com")

50

.append("active", true);

51

52

// Nested document

53

Document address = new Document("street", "123 Main St")

54

.append("city", "Springfield")

55

.append("zipCode", "12345");

56

user.append("address", address);

57

58

// Array field

59

user.append("hobbies", Arrays.asList("reading", "swimming", "cooking"));

60

61

// Convert to JSON

62

String json = user.toJson();

63

System.out.println(json);

64

65

// Parse from JSON

66

Document parsed = Document.parse(json);

67

68

// Type-safe field access

69

String name = user.getString("name");

70

Integer age = user.getInteger("age");

71

Document userAddress = user.get("address", Document.class);

72

```

73

74

### BsonDocument Class

75

76

Type-safe BSON document with strongly-typed field access and BSON value hierarchy integration.

77

78

```java { .api }

79

/**

80

* Type-safe BSON document implementation

81

*/

82

public class BsonDocument extends BsonValue implements Map<String, BsonValue>, Cloneable {

83

// Constructors

84

public BsonDocument();

85

public BsonDocument(String key, BsonValue value);

86

public BsonDocument(List<BsonElement> bsonElements);

87

88

// Fluent building

89

public BsonDocument append(String key, BsonValue value);

90

91

// Map operations

92

public BsonValue get(Object key);

93

public BsonValue put(String key, BsonValue value);

94

public Set<String> keySet();

95

public Collection<BsonValue> values();

96

public Set<Entry<String, BsonValue>> entrySet();

97

98

// Utility methods

99

public String getFirstKey();

100

public boolean isEmpty();

101

public int size();

102

public BsonDocument clone();

103

104

// Type checking from BsonValue

105

public BsonType getBsonType(); // Returns DOCUMENT

106

public boolean isDocument();

107

public BsonDocument asDocument();

108

}

109

```

110

111

### BsonValue Hierarchy

112

113

Abstract base class for all strongly-typed BSON values with type checking and conversion methods.

114

115

```java { .api }

116

/**

117

* Abstract base class for all BSON values

118

*/

119

public abstract class BsonValue {

120

public abstract BsonType getBsonType();

121

122

// Type checking methods

123

public boolean isArray();

124

public boolean isBinary();

125

public boolean isBoolean();

126

public boolean isDateTime();

127

public boolean isDocument();

128

public boolean isDouble();

129

public boolean isInt32();

130

public boolean isInt64();

131

public boolean isNull();

132

public boolean isNumber();

133

public boolean isObjectId();

134

public boolean isString();

135

public boolean isTimestamp();

136

137

// Type conversion methods

138

public BsonArray asArray();

139

public BsonBinary asBinary();

140

public BsonBoolean asBoolean();

141

public BsonDateTime asDateTime();

142

public BsonDocument asDocument();

143

public BsonDouble asDouble();

144

public BsonInt32 asInt32();

145

public BsonInt64 asInt64();

146

public BsonNull asNull();

147

public BsonNumber asNumber();

148

public BsonObjectId asObjectId();

149

public BsonString asString();

150

public BsonTimestamp asTimestamp();

151

}

152

```

153

154

### Primitive BSON Types

155

156

Strongly-typed BSON primitive value implementations.

157

158

```java { .api }

159

/**

160

* BSON string value

161

*/

162

public class BsonString extends BsonValue {

163

public BsonString(String value);

164

public String getValue();

165

public BsonType getBsonType(); // Returns STRING

166

}

167

168

/**

169

* BSON 32-bit integer value

170

*/

171

public class BsonInt32 extends BsonNumber {

172

public BsonInt32(int value);

173

public int getValue();

174

public BsonType getBsonType(); // Returns INT32

175

}

176

177

/**

178

* BSON 64-bit integer value

179

*/

180

public class BsonInt64 extends BsonNumber {

181

public BsonInt64(long value);

182

public long getValue();

183

public BsonType getBsonType(); // Returns INT64

184

}

185

186

/**

187

* BSON double-precision floating point value

188

*/

189

public class BsonDouble extends BsonNumber {

190

public BsonDouble(double value);

191

public double getValue();

192

public BsonType getBsonType(); // Returns DOUBLE

193

}

194

195

/**

196

* BSON boolean value

197

*/

198

public class BsonBoolean extends BsonValue {

199

public static final BsonBoolean TRUE;

200

public static final BsonBoolean FALSE;

201

202

public BsonBoolean(boolean value);

203

public boolean getValue();

204

public BsonType getBsonType(); // Returns BOOLEAN

205

}

206

207

/**

208

* BSON null value

209

*/

210

public class BsonNull extends BsonValue {

211

public static final BsonNull VALUE;

212

213

public BsonType getBsonType(); // Returns NULL

214

}

215

```

216

217

### Complex BSON Types

218

219

BSON array, binary data, and specialized types.

220

221

```java { .api }

222

/**

223

* BSON array value implementing List<BsonValue>

224

*/

225

public class BsonArray extends BsonValue implements List<BsonValue>, Cloneable {

226

public BsonArray();

227

public BsonArray(List<? extends BsonValue> list);

228

229

// List interface methods

230

public boolean add(BsonValue bsonValue);

231

public void add(int index, BsonValue element);

232

public BsonValue get(int index);

233

public BsonValue set(int index, BsonValue element);

234

public int size();

235

public boolean isEmpty();

236

237

// Type-specific methods

238

public BsonType getBsonType(); // Returns ARRAY

239

public BsonArray clone();

240

}

241

242

/**

243

* BSON binary data value

244

*/

245

public class BsonBinary extends BsonValue {

246

public BsonBinary(byte[] data);

247

public BsonBinary(BsonBinarySubType type, byte[] data);

248

249

public byte[] getData();

250

public BsonBinarySubType getType();

251

public BsonType getBsonType(); // Returns BINARY

252

}

253

254

/**

255

* BSON ObjectId value

256

*/

257

public class BsonObjectId extends BsonValue implements Comparable<BsonObjectId> {

258

public BsonObjectId();

259

public BsonObjectId(ObjectId value);

260

261

public ObjectId getValue();

262

public BsonType getBsonType(); // Returns OBJECT_ID

263

public int compareTo(BsonObjectId other);

264

}

265

266

/**

267

* BSON date/time value

268

*/

269

public class BsonDateTime extends BsonValue {

270

public BsonDateTime(long value);

271

public BsonDateTime(Date date);

272

273

public long getValue(); // Milliseconds since Unix epoch

274

public BsonType getBsonType(); // Returns DATE_TIME

275

}

276

277

/**

278

* BSON regular expression value

279

*/

280

public class BsonRegularExpression extends BsonValue {

281

public BsonRegularExpression(String pattern);

282

public BsonRegularExpression(String pattern, String options);

283

284

public String getPattern();

285

public String getOptions();

286

public BsonType getBsonType(); // Returns REGULAR_EXPRESSION

287

}

288

```

289

290

### ObjectId

291

292

MongoDB's unique identifier type with timestamp and uniqueness guarantees.

293

294

```java { .api }

295

/**

296

* MongoDB ObjectId - 12-byte unique identifier

297

*/

298

public class ObjectId implements Comparable<ObjectId>, Serializable {

299

// Constructors

300

public ObjectId();

301

public ObjectId(Date date);

302

public ObjectId(String hexString);

303

public ObjectId(byte[] bytes);

304

public ObjectId(int timestamp, int randomValue1, short randomValue2, int counter);

305

306

// String conversion

307

public String toHexString();

308

public static boolean isValid(String hexString);

309

310

// Timestamp extraction

311

public Date getDate();

312

public int getTimestamp();

313

314

// Comparison and equality

315

public int compareTo(ObjectId other);

316

public boolean equals(Object obj);

317

public int hashCode();

318

319

// Byte representation

320

public byte[] toByteArray();

321

}

322

```

323

324

**ObjectId Usage Examples:**

325

326

```java

327

// Generate new ObjectId

328

ObjectId id = new ObjectId();

329

System.out.println("Generated ID: " + id.toHexString());

330

331

// Create from string

332

ObjectId parsed = new ObjectId("507f1f77bcf86cd799439011");

333

334

// Extract timestamp

335

Date creationTime = id.getDate();

336

System.out.println("Created at: " + creationTime);

337

338

// Validate ObjectId string

339

if (ObjectId.isValid("507f1f77bcf86cd799439011")) {

340

ObjectId valid = new ObjectId("507f1f77bcf86cd799439011");

341

}

342

```

343

344

### BsonType Enumeration

345

346

Enumeration of all BSON data types for type checking and switching.

347

348

```java { .api }

349

/**

350

* Enumeration of BSON types

351

*/

352

public enum BsonType {

353

END_OF_DOCUMENT(0),

354

DOUBLE(1),

355

STRING(2),

356

DOCUMENT(3),

357

ARRAY(4),

358

BINARY(5),

359

UNDEFINED(6), // Deprecated

360

OBJECT_ID(7),

361

BOOLEAN(8),

362

DATE_TIME(9),

363

NULL(10),

364

REGULAR_EXPRESSION(11),

365

DB_POINTER(12), // Deprecated

366

JAVASCRIPT(13),

367

SYMBOL(14), // Deprecated

368

JAVASCRIPT_WITH_SCOPE(15), // Deprecated

369

INT32(16),

370

TIMESTAMP(17),

371

INT64(18),

372

DECIMAL128(19),

373

MIN_KEY(-1),

374

MAX_KEY(127);

375

376

public int getValue();

377

public static BsonType findByValue(int value);

378

}

379

```

380

381

### Codec System Integration

382

383

Integration with MongoDB's codec system for custom serialization.

384

385

```java { .api }

386

/**

387

* Codec for Document class

388

*/

389

public class DocumentCodec implements CollectibleCodec<Document> {

390

public DocumentCodec();

391

public DocumentCodec(BsonTypeClassMap bsonTypeClassMap);

392

public DocumentCodec(CodecRegistry registry, BsonTypeClassMap bsonTypeClassMap);

393

394

public void encode(BsonWriter writer, Document document, EncoderContext encoderContext);

395

public Document decode(BsonReader reader, DecoderContext decoderContext);

396

public Class<Document> getEncoderClass();

397

}

398

399

/**

400

* Codec for BsonDocument class

401

*/

402

public class BsonDocumentCodec implements Codec<BsonDocument> {

403

public static final BsonDocumentCodec DEFAULT;

404

405

public void encode(BsonWriter writer, BsonDocument document, EncoderContext encoderContext);

406

public BsonDocument decode(BsonReader reader, DecoderContext decoderContext);

407

public Class<BsonDocument> getEncoderClass();

408

}

409

```

410

411

**Custom Codec Example:**

412

413

```java

414

// Create custom codec registry

415

CodecRegistry defaultCodecRegistry = MongoClientSettings.getDefaultCodecRegistry();

416

CodecRegistry customCodecRegistry = fromRegistries(

417

defaultCodecRegistry,

418

fromCodecs(new MyCustomCodec())

419

);

420

421

// Use with collection

422

MongoCollection<MyCustomType> collection = database

423

.getCollection("mycollection", MyCustomType.class)

424

.withCodecRegistry(customCodecRegistry);

425

```

426

427

## Types

428

429

```java { .api }

430

/**

431

* Element in a BSON document (key-value pair)

432

*/

433

public class BsonElement {

434

public BsonElement(String name, BsonValue value);

435

436

public String getName();

437

public BsonValue getValue();

438

}

439

440

/**

441

* Binary data subtype enumeration

442

*/

443

public enum BsonBinarySubType {

444

BINARY(0),

445

FUNCTION(1),

446

BINARY_OLD(2), // Deprecated

447

UUID_LEGACY(3), // Deprecated

448

UUID_STANDARD(4),

449

MD5(5),

450

ENCRYPTED(6),

451

USER_DEFINED(128);

452

453

public byte getValue();

454

public static BsonBinarySubType forValue(byte value);

455

}

456

457

/**

458

* BSON timestamp type for MongoDB internal use

459

*/

460

public class BsonTimestamp extends BsonValue implements Comparable<BsonTimestamp> {

461

public BsonTimestamp();

462

public BsonTimestamp(int time, int inc);

463

public BsonTimestamp(long value);

464

465

public int getTime();

466

public int getInc();

467

public long getValue();

468

public BsonType getBsonType(); // Returns TIMESTAMP

469

}

470

```