0
# Legacy BSON API
1
2
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.
3
4
## BSONObject Interface
5
6
The `BSONObject` interface represents the core abstraction for BSON documents in the legacy API.
7
8
```java { .api }
9
public interface BSONObject {
10
/**
11
* Sets a name/value pair in this object.
12
* @param key name of the field
13
* @param v value of the field
14
* @return the old value for the field, or null if none existed
15
*/
16
Object put(String key, Object v);
17
18
/**
19
* Sets all key/value pairs from a map into this object.
20
* @param m the map of key/value pairs
21
*/
22
void putAll(Map<String, ? extends Object> m);
23
24
/**
25
* Gets a field from this object by a given name.
26
* @param key the name of the field to fetch
27
* @return the field, if found
28
*/
29
Object get(String key);
30
31
/**
32
* Returns a map representing this BSONObject.
33
* @return the map
34
*/
35
Map toMap();
36
37
/**
38
* Removes a field with a given name from this object.
39
* @param key the name of the field to remove
40
* @return the object removed
41
*/
42
Object removeField(String key);
43
44
/**
45
* Checks if this object contains a field with the given name.
46
* @param s field name for which to check
47
* @return true if the field name exists
48
*/
49
boolean containsField(String s);
50
51
/**
52
* Returns this object's fields' names.
53
* @return set of field names
54
*/
55
Set<String> keySet();
56
57
/**
58
* Marks this object as partial.
59
* @param b whether or not this object is partial
60
*/
61
void markAsPartialObject(boolean b);
62
63
/**
64
* Whether or not this object has been marked as partial.
65
* @return true if this object is partial
66
*/
67
boolean isPartialObject();
68
}
69
```
70
71
## BasicBSONObject
72
73
The `BasicBSONObject` class is the primary implementation of `BSONObject`.
74
75
```java { .api }
76
public class BasicBSONObject implements BSONObject, Map<String, Object>, Serializable {
77
/**
78
* Creates an empty object.
79
*/
80
public BasicBSONObject();
81
82
/**
83
* Creates a BasicBSONObject from a map of key-value pairs.
84
* @param m map of key-value pairs
85
*/
86
public BasicBSONObject(Map<String, Object> m);
87
88
/**
89
* Creates an object with the given key/value.
90
* @param key key under which to store
91
* @param value value to store
92
*/
93
public BasicBSONObject(String key, Object value);
94
95
/**
96
* Creates an object from a string representation.
97
* @param s the string representation
98
* @return the BasicBSONObject
99
*/
100
public static BasicBSONObject parse(String s);
101
102
// BSONObject implementation
103
public Object put(String key, Object v);
104
public void putAll(Map<String, ? extends Object> m);
105
public Object get(String key);
106
public Map toMap();
107
public Object removeField(String key);
108
public boolean containsField(String s);
109
public Set<String> keySet();
110
public void markAsPartialObject(boolean b);
111
public boolean isPartialObject();
112
113
// Map interface implementation
114
public int size();
115
public boolean isEmpty();
116
public boolean containsValue(Object value);
117
public Object remove(Object key);
118
public void clear();
119
public Collection<Object> values();
120
public Set<Map.Entry<String, Object>> entrySet();
121
122
/**
123
* Returns a JSON representation of this object.
124
* @return the JSON string
125
*/
126
public String toJson();
127
128
/**
129
* Appends a key/value pair to this object.
130
* @param key the name of the field
131
* @param val the value of the field
132
* @return this object
133
*/
134
public BasicBSONObject append(String key, Object val);
135
136
/**
137
* Gets a value by key and casts it to the specified type.
138
* @param key the key
139
* @param clazz the class to cast to
140
* @param <T> the type
141
* @return the value cast to type T
142
*/
143
public <T> T get(String key, Class<T> clazz);
144
145
/**
146
* Gets a value by key as a String.
147
* @param key the key
148
* @return the value as a String
149
*/
150
public String getString(String key);
151
152
/**
153
* Gets a value by key as a String, with a default value.
154
* @param key the key
155
* @param def the default value
156
* @return the value as a String, or the default if not found
157
*/
158
public String getString(String key, String def);
159
160
/**
161
* Gets a value by key as an int.
162
* @param key the key
163
* @return the value as an int
164
*/
165
public int getInt(String key);
166
167
/**
168
* Gets a value by key as an int, with a default value.
169
* @param key the key
170
* @param def the default value
171
* @return the value as an int, or the default if not found
172
*/
173
public int getInt(String key, int def);
174
175
/**
176
* Gets a value by key as a long.
177
* @param key the key
178
* @return the value as a long
179
*/
180
public long getLong(String key);
181
182
/**
183
* Gets a value by key as a long, with a default value.
184
* @param key the key
185
* @param def the default value
186
* @return the value as a long, or the default if not found
187
*/
188
public long getLong(String key, long def);
189
190
/**
191
* Gets a value by key as a double.
192
* @param key the key
193
* @return the value as a double
194
*/
195
public double getDouble(String key);
196
197
/**
198
* Gets a value by key as a double, with a default value.
199
* @param key the key
200
* @param def the default value
201
* @return the value as a double, or the default if not found
202
*/
203
public double getDouble(String key, double def);
204
205
/**
206
* Gets a value by key as a boolean.
207
* @param key the key
208
* @return the value as a boolean
209
*/
210
public boolean getBoolean(String key);
211
212
/**
213
* Gets a value by key as a boolean, with a default value.
214
* @param key the key
215
* @param def the default value
216
* @return the value as a boolean, or the default if not found
217
*/
218
public boolean getBoolean(String key, boolean def);
219
220
/**
221
* Gets a value by key as an ObjectId.
222
* @param key the key
223
* @return the value as an ObjectId
224
*/
225
public ObjectId getObjectId(String key);
226
227
/**
228
* Gets a value by key as an ObjectId, with a default value.
229
* @param key the key
230
* @param def the default value
231
* @return the value as an ObjectId, or the default if not found
232
*/
233
public ObjectId getObjectId(String key, ObjectId def);
234
235
/**
236
* Gets a value by key as a Date.
237
* @param key the key
238
* @return the value as a Date
239
*/
240
public Date getDate(String key);
241
242
/**
243
* Gets a value by key as a Date, with a default value.
244
* @param key the key
245
* @param def the default value
246
* @return the value as a Date, or the default if not found
247
*/
248
public Date getDate(String key, Date def);
249
250
public boolean equals(Object o);
251
public int hashCode();
252
public String toString();
253
}
254
```
255
256
## BasicBSONList
257
258
The `BasicBSONList` class represents a BSON array in the legacy API.
259
260
```java { .api }
261
public class BasicBSONList extends ArrayList<Object> implements BSONObject {
262
/**
263
* Creates an empty BasicBSONList.
264
*/
265
public BasicBSONList();
266
267
/**
268
* Puts a value at the given index.
269
* @param key the index as a string
270
* @param v the value
271
* @return the previous value at that index
272
*/
273
public Object put(String key, Object v);
274
275
/**
276
* Puts a value at the given numeric index.
277
* @param i the index
278
* @param v the value
279
* @return the previous value at that index
280
*/
281
public Object put(int i, Object v);
282
283
/**
284
* Gets a value by string index.
285
* @param key the index as a string
286
* @return the value at that index
287
*/
288
public Object get(String key);
289
290
/**
291
* Removes a field by string index.
292
* @param key the index as a string
293
* @return the removed value
294
*/
295
public Object removeField(String key);
296
297
/**
298
* Checks if a field exists by string index.
299
* @param s the index as a string
300
* @return true if the field exists
301
*/
302
public boolean containsField(String s);
303
304
/**
305
* Gets all string indices as a set.
306
* @return set of string indices
307
*/
308
public Set<String> keySet();
309
310
public void putAll(Map<String, ? extends Object> m);
311
public Map<String, Object> toMap();
312
public void markAsPartialObject(boolean b);
313
public boolean isPartialObject();
314
}
315
```
316
317
## BSON Encoding/Decoding
318
319
### BSONEncoder Interface
320
321
```java { .api }
322
public interface BSONEncoder {
323
/**
324
* Encodes a BSONObject.
325
* @param o the BSONObject to encode
326
* @return the encoded bytes
327
*/
328
byte[] encode(BSONObject o);
329
330
/**
331
* Encodes a BSONObject and writes to the provided output stream.
332
* @param o the BSONObject to encode
333
* @param buf the output buffer
334
* @return the number of bytes written
335
*/
336
int encode(BSONObject o, OutputBuffer buf);
337
338
/**
339
* Sets the encoder factory.
340
* @param factory the encoder factory
341
*/
342
void set(BSONEncoderFactory factory);
343
}
344
```
345
346
### BSONDecoder Interface
347
348
```java { .api }
349
public interface BSONDecoder {
350
/**
351
* Decodes a BSON byte array into a BSONObject.
352
* @param b the byte array
353
* @return the decoded BSONObject
354
*/
355
BSONObject decode(byte[] b);
356
357
/**
358
* Decodes BSON data from an input stream.
359
* @param in the input stream
360
* @return the decoded BSONObject
361
*/
362
BSONObject decode(InputStream in);
363
364
/**
365
* Reads a single BSON object from the input stream.
366
* @param in the input stream
367
* @param collection the collection name (may be null)
368
* @return the decoded BSONObject
369
*/
370
BSONObject readObject(InputStream in, String collection);
371
372
/**
373
* Reads a single BSON object from a byte buffer.
374
* @param buf the byte buffer
375
* @return the decoded BSONObject
376
*/
377
BSONObject readObject(ByteBuffer buf);
378
379
/**
380
* Gets the decoder factory.
381
* @return the decoder factory
382
*/
383
BSONDecoderFactory getDBDecoderFactory();
384
385
/**
386
* Sets the decoder factory.
387
* @param factory the decoder factory
388
*/
389
void setDBDecoderFactory(BSONDecoderFactory factory);
390
}
391
```
392
393
### BasicBSONEncoder
394
395
```java { .api }
396
public class BasicBSONEncoder implements BSONEncoder {
397
/**
398
* Creates a new BasicBSONEncoder.
399
*/
400
public BasicBSONEncoder();
401
402
public byte[] encode(BSONObject o);
403
public int encode(BSONObject o, OutputBuffer buf);
404
public void set(BSONEncoderFactory factory);
405
406
/**
407
* Encodes a BSONObject and returns the encoded length.
408
* @param o the BSONObject to encode
409
* @param buf the output buffer
410
* @return the encoded length
411
*/
412
protected int putObject(BSONObject o, OutputBuffer buf);
413
414
/**
415
* Encodes a string.
416
* @param s the string
417
* @param buf the output buffer
418
*/
419
protected void putString(String s, OutputBuffer buf);
420
421
/**
422
* Encodes a string with null termination.
423
* @param s the string
424
* @param buf the output buffer
425
*/
426
protected void putCString(String s, OutputBuffer buf);
427
}
428
```
429
430
### BasicBSONDecoder
431
432
```java { .api }
433
public class BasicBSONDecoder implements BSONDecoder {
434
/**
435
* Creates a new BasicBSONDecoder.
436
*/
437
public BasicBSONDecoder();
438
439
public BSONObject decode(byte[] b);
440
public BSONObject decode(InputStream in);
441
public BSONObject readObject(InputStream in, String collection);
442
public BSONObject readObject(ByteBuffer buf);
443
public BSONDecoderFactory getDBDecoderFactory();
444
public void setDBDecoderFactory(BSONDecoderFactory factory);
445
446
/**
447
* Reads an object from the byte buffer.
448
* @param buf the byte buffer
449
* @param callback the callback for handling the object
450
* @return the number of bytes read
451
*/
452
public int decode(ByteBuffer buf, BSONCallback callback);
453
454
/**
455
* Reads a string from the buffer.
456
* @param buf the byte buffer
457
* @param stringCodec the string codec to use
458
* @return the decoded string
459
*/
460
protected String readString(ByteBuffer buf, StringCodec stringCodec);
461
462
/**
463
* Reads a C-style null-terminated string.
464
* @param buf the byte buffer
465
* @param stringCodec the string codec to use
466
* @return the decoded string
467
*/
468
protected String readCString(ByteBuffer buf, StringCodec stringCodec);
469
}
470
```
471
472
## BSON Callback System
473
474
### BSONCallback Interface
475
476
```java { .api }
477
public interface BSONCallback {
478
/**
479
* Called when the start of a BSON object is encountered.
480
* @return the object created for this BSON object
481
*/
482
BSONObject objectStart();
483
484
/**
485
* Called when the start of a BSON object is encountered with a name.
486
* @param name the name of the object
487
* @param embedded true if this is an embedded object
488
* @return the object created for this BSON object
489
*/
490
BSONObject objectStart(String name, boolean embedded);
491
492
/**
493
* Called when the end of a BSON object is encountered.
494
* @param o the BSON object that is ending
495
* @return the finished object
496
*/
497
Object objectDone(BSONObject o);
498
499
/**
500
* Called when the start of a BSON array is encountered.
501
* @return the array object
502
*/
503
BSONObject arrayStart();
504
505
/**
506
* Called when the start of a BSON array is encountered with a name.
507
* @param name the name of the array
508
* @return the array object
509
*/
510
BSONObject arrayStart(String name);
511
512
/**
513
* Called when the end of a BSON array is encountered.
514
* @param array the array that is ending
515
* @return the finished array
516
*/
517
Object arrayDone(BSONObject array);
518
519
/**
520
* Called when a field is encountered.
521
* @param o the containing object
522
* @param name the field name
523
* @param value the field value
524
* @throws BSONException if an error occurs
525
*/
526
void gotNull(String name);
527
void gotBoolean(String name, boolean value);
528
void gotDouble(String name, double value);
529
void gotInt(String name, int value);
530
void gotLong(String name, long value);
531
void gotDate(String name, long millis);
532
void gotString(String name, String value);
533
void gotSymbol(String name, String value);
534
void gotRegex(String name, String pattern, String flags);
535
void gotTimestamp(String name, int time, int increment);
536
void gotObjectId(String name, ObjectId id);
537
void gotDBRef(String name, String namespace, ObjectId id);
538
void gotBinaryArray(String name, byte[] data);
539
void gotBinary(String name, byte type, byte[] data);
540
void gotUUID(String name, long part1, long part2);
541
void gotCode(String name, String code);
542
void gotCodeWScope(String name, String code, Object scope);
543
544
/**
545
* Resets the callback.
546
*/
547
void reset();
548
549
/**
550
* Gets the root object.
551
* @return the root object
552
*/
553
Object get();
554
555
/**
556
* Creates a BSON object.
557
* @param embedded true if this is an embedded object
558
* @param path the path to this object
559
* @return the BSON object
560
*/
561
BSONObject create(boolean embedded, String path);
562
563
/**
564
* Creates a BSON list.
565
* @param path the path to this list
566
* @return the BSON list
567
*/
568
BSONObject createList(String path);
569
}
570
```
571
572
### BasicBSONCallback
573
574
```java { .api }
575
public class BasicBSONCallback implements BSONCallback {
576
/**
577
* Creates a new BasicBSONCallback.
578
*/
579
public BasicBSONCallback();
580
581
// BSONCallback implementation
582
public BSONObject objectStart();
583
public BSONObject objectStart(String name, boolean embedded);
584
public Object objectDone(BSONObject o);
585
public BSONObject arrayStart();
586
public BSONObject arrayStart(String name);
587
public Object arrayDone(BSONObject array);
588
589
public void gotNull(String name);
590
public void gotBoolean(String name, boolean value);
591
public void gotDouble(String name, double value);
592
public void gotInt(String name, int value);
593
public void gotLong(String name, long value);
594
public void gotDate(String name, long millis);
595
public void gotString(String name, String value);
596
public void gotSymbol(String name, String value);
597
public void gotRegex(String name, String pattern, String flags);
598
public void gotTimestamp(String name, int time, int increment);
599
public void gotObjectId(String name, ObjectId id);
600
public void gotDBRef(String name, String namespace, ObjectId id);
601
public void gotBinaryArray(String name, byte[] data);
602
public void gotBinary(String name, byte type, byte[] data);
603
public void gotUUID(String name, long part1, long part2);
604
public void gotCode(String name, String code);
605
public void gotCodeWScope(String name, String code, Object scope);
606
607
public void reset();
608
public Object get();
609
public BSONObject create(boolean embedded, String path);
610
public BSONObject createList(String path);
611
612
/**
613
* Creates a BSON object for the given path.
614
* @param embedded true if this is an embedded object
615
* @param path the path
616
* @return the BSON object
617
*/
618
public BSONObject createObject(String path);
619
620
/**
621
* Gets the current object being processed.
622
* @return the current object
623
*/
624
public BSONObject getCurrent();
625
626
/**
627
* Gets the current field name being processed.
628
* @return the current field name
629
*/
630
public String getCurName();
631
632
/**
633
* Sets a field in the current object.
634
* @param name the field name
635
* @param value the field value
636
*/
637
public void setCurrentObject(String name, Object value);
638
}
639
```
640
641
## BSON Utility Class
642
643
```java { .api }
644
public final class BSON {
645
/**
646
* Regular expression type.
647
*/
648
public static final byte REGEX = 11;
649
650
/**
651
* Array type.
652
*/
653
public static final byte ARRAY = 4;
654
655
/**
656
* Object type.
657
*/
658
public static final byte OBJECT = 3;
659
660
/**
661
* Encodes a BSONObject to bytes.
662
* @param obj the BSONObject to encode
663
* @return the encoded bytes
664
*/
665
public static byte[] encode(BSONObject obj);
666
667
/**
668
* Decodes bytes to a BSONObject.
669
* @param bytes the bytes to decode
670
* @return the decoded BSONObject
671
*/
672
public static BSONObject decode(byte[] bytes);
673
674
/**
675
* Adds an encoding hook.
676
* @param clazz the class to add the hook for
677
* @param transformer the transformer
678
*/
679
public static void addEncodingHook(Class clazz, Transformer transformer);
680
681
/**
682
* Adds a decoding hook.
683
* @param clazz the class to add the hook for
684
* @param transformer the transformer
685
*/
686
public static void addDecodingHook(Class clazz, Transformer transformer);
687
688
/**
689
* Removes encoding hooks for the given class.
690
* @param clazz the class
691
*/
692
public static void removeEncodingHooks(Class clazz);
693
694
/**
695
* Removes decoding hooks for the given class.
696
* @param clazz the class
697
*/
698
public static void removeDecodingHooks(Class clazz);
699
700
/**
701
* Gets the encoding hooks for the given class.
702
* @param clazz the class
703
* @return list of transformers
704
*/
705
public static List<Transformer> getEncodingHooks(Class clazz);
706
707
/**
708
* Gets the decoding hooks for the given class.
709
* @param clazz the class
710
* @return list of transformers
711
*/
712
public static List<Transformer> getDecodingHooks(Class clazz);
713
714
/**
715
* Clears all encoding and decoding hooks.
716
*/
717
public static void clearAllHooks();
718
}
719
```
720
721
## Usage Examples
722
723
### Basic Document Operations
724
725
```java
726
import org.bson.*;
727
import org.bson.types.ObjectId;
728
729
// Create a BasicBSONObject
730
BasicBSONObject person = new BasicBSONObject();
731
person.put("_id", new ObjectId());
732
person.put("name", "John Doe");
733
person.put("age", 30);
734
person.put("active", true);
735
736
// Chain operations
737
BasicBSONObject address = new BasicBSONObject("street", "123 Main St")
738
.append("city", "Anytown")
739
.append("zip", "12345");
740
person.put("address", address);
741
742
// Type-safe getters
743
String name = person.getString("name");
744
int age = person.getInt("age");
745
boolean active = person.getBoolean("active");
746
ObjectId id = person.getObjectId("_id");
747
748
// Convert to JSON
749
String json = person.toJson();
750
```
751
752
### Working with Arrays
753
754
```java
755
// Create a BasicBSONList
756
BasicBSONList skills = new BasicBSONList();
757
skills.add("Java");
758
skills.add("MongoDB");
759
skills.add("BSON");
760
761
// Add to document
762
BasicBSONObject developer = new BasicBSONObject("name", "Alice")
763
.append("skills", skills);
764
765
// Access array elements
766
String firstSkill = (String) skills.get(0);
767
int skillCount = skills.size();
768
769
// Iterate over array
770
for (Object skill : skills) {
771
System.out.println(skill);
772
}
773
```
774
775
### Encoding and Decoding
776
777
```java
778
import org.bson.*;
779
780
// Create a document
781
BasicBSONObject document = new BasicBSONObject("message", "Hello BSON")
782
.append("timestamp", System.currentTimeMillis())
783
.append("version", 1);
784
785
// Encode to bytes
786
BasicBSONEncoder encoder = new BasicBSONEncoder();
787
byte[] encodedData = encoder.encode(document);
788
789
// Decode from bytes
790
BasicBSONDecoder decoder = new BasicBSONDecoder();
791
BSONObject decodedDocument = decoder.decode(encodedData);
792
793
// Verify data
794
String message = (String) decodedDocument.get("message");
795
Long timestamp = (Long) decodedDocument.get("timestamp");
796
```
797
798
### Custom Callbacks
799
800
```java
801
import org.bson.*;
802
803
// Custom callback for processing specific fields
804
class CustomBSONCallback extends BasicBSONCallback {
805
@Override
806
public void gotString(String name, String value) {
807
if ("email".equals(name)) {
808
// Validate email format
809
if (!value.contains("@")) {
810
throw new BSONException("Invalid email format: " + value);
811
}
812
}
813
super.gotString(name, value);
814
}
815
816
@Override
817
public void gotInt(String name, int value) {
818
if ("age".equals(name) && value < 0) {
819
throw new BSONException("Age cannot be negative: " + value);
820
}
821
super.gotInt(name, value);
822
}
823
}
824
825
// Use custom callback
826
BasicBSONDecoder decoder = new BasicBSONDecoder();
827
CustomBSONCallback callback = new CustomBSONCallback();
828
decoder.decode(bsonData, callback);
829
BSONObject validatedObject = (BSONObject) callback.get();
830
```
831
832
### Migration from Legacy to Modern API
833
834
```java
835
// Legacy API
836
BasicBSONObject legacyDoc = new BasicBSONObject("name", "example")
837
.append("value", 42);
838
839
// Convert to modern API
840
Document modernDoc = new Document(legacyDoc.toMap());
841
842
// Or create BsonDocument
843
BsonDocument bsonDoc = new BsonDocument();
844
for (String key : legacyDoc.keySet()) {
845
Object value = legacyDoc.get(key);
846
if (value instanceof String) {
847
bsonDoc.put(key, new BsonString((String) value));
848
} else if (value instanceof Integer) {
849
bsonDoc.put(key, new BsonInt32((Integer) value));
850
}
851
// Handle other types as needed
852
}
853
```
854
855
### Working with Nested Documents
856
857
```java
858
// Create nested structure
859
BasicBSONObject user = new BasicBSONObject();
860
user.put("_id", new ObjectId());
861
user.put("username", "johndoe");
862
863
BasicBSONObject profile = new BasicBSONObject();
864
profile.put("firstName", "John");
865
profile.put("lastName", "Doe");
866
profile.put("email", "john@example.com");
867
868
BasicBSONObject preferences = new BasicBSONObject();
869
preferences.put("theme", "dark");
870
preferences.put("notifications", true);
871
profile.put("preferences", preferences);
872
873
user.put("profile", profile);
874
875
// Access nested values
876
BasicBSONObject userProfile = (BasicBSONObject) user.get("profile");
877
String firstName = userProfile.getString("firstName");
878
879
BasicBSONObject userPrefs = (BasicBSONObject) userProfile.get("preferences");
880
String theme = userPrefs.getString("theme");
881
```