0
# Specialized Data Types
1
2
The BSON library provides specialized data types for MongoDB-specific values and advanced data modeling. These types handle unique identifiers, high-precision decimals, binary data, timestamps, and other specialized BSON types that extend beyond basic JSON capabilities.
3
4
## ObjectId
5
6
The `ObjectId` class represents MongoDB's unique identifier type, which is a 12-byte identifier consisting of a timestamp, machine identifier, process identifier, and counter.
7
8
```java { .api }
9
public final class ObjectId implements Comparable<ObjectId>, Serializable {
10
/**
11
* Constructs a new instance using the current time, machine identifier, process identifier, and a counter.
12
*/
13
public ObjectId();
14
15
/**
16
* Constructs a new instance from the given byte array.
17
* @param bytes the byte array
18
* @throws IllegalArgumentException if the byte array is not of length 12
19
*/
20
public ObjectId(byte[] bytes);
21
22
/**
23
* Constructs a new instance from the given ByteBuffer.
24
* @param buffer the ByteBuffer
25
* @throws IllegalArgumentException if the buffer does not have 12 remaining bytes
26
*/
27
public ObjectId(ByteBuffer buffer);
28
29
/**
30
* Constructs a new instance from a 24-character hexadecimal string representation.
31
* @param hexString the string to convert
32
* @throws IllegalArgumentException if the string is not a valid hex string representation of an ObjectId
33
*/
34
public ObjectId(String hexString);
35
36
/**
37
* Constructs a new instance using the given date.
38
* @param date the date
39
*/
40
public ObjectId(Date date);
41
42
/**
43
* Constructs a new instance using the given date and counter.
44
* @param date the date
45
* @param counter the counter
46
* @throws IllegalArgumentException if the high order byte of counter is not 0
47
*/
48
public ObjectId(Date date, int counter);
49
50
/**
51
* Constructs a new instance.
52
* @param timestamp the timestamp (seconds since epoch)
53
* @param machineAndProcessIdentifier the machine and process identifier
54
* @param counter the counter
55
* @throws IllegalArgumentException if the high order byte of counter is not 0
56
*/
57
public ObjectId(int timestamp, int machineAndProcessIdentifier, int counter);
58
59
/**
60
* Gets the timestamp (seconds since epoch).
61
* @return the timestamp
62
*/
63
public int getTimestamp();
64
65
/**
66
* Gets the machine identifier.
67
* @return the machine identifier
68
*/
69
public int getMachineIdentifier();
70
71
/**
72
* Gets the process identifier.
73
* @return the process identifier
74
*/
75
public int getProcessIdentifier();
76
77
/**
78
* Gets the counter.
79
* @return the counter
80
*/
81
public int getCounter();
82
83
/**
84
* Gets the timestamp as a Date instance.
85
* @return the Date
86
*/
87
public Date getDate();
88
89
/**
90
* Converts this instance to a 24-character hexadecimal string representation.
91
* @return the hexadecimal string representation
92
*/
93
public String toHexString();
94
95
/**
96
* Convert to a byte array. Note that the numbers are stored in big-endian order.
97
* @return the byte array
98
*/
99
public byte[] toByteArray();
100
101
/**
102
* Gets a new ObjectId with the current date/time.
103
* @return the ObjectId
104
*/
105
public static ObjectId get();
106
107
/**
108
* Checks if a string could be an ObjectId.
109
* @param hexString a potential ObjectId as a String
110
* @return whether the string could be an object id
111
* @throws IllegalArgumentException if hexString is null
112
*/
113
public static boolean isValid(String hexString);
114
115
/**
116
* Gets the generated machine identifier.
117
* @return an int representing the machine identifier
118
*/
119
public static int getGeneratedMachineIdentifier();
120
121
/**
122
* Gets the current process identifier.
123
* @return the process id
124
*/
125
public static int getCurrentProcessId();
126
127
public int compareTo(ObjectId other);
128
public boolean equals(Object o);
129
public int hashCode();
130
public String toString();
131
}
132
```
133
134
## Decimal128
135
136
The `Decimal128` class represents a 128-bit decimal floating point value, which provides exact decimal representation for financial and monetary calculations.
137
138
```java { .api }
139
public final class Decimal128 implements Comparable<Decimal128> {
140
/**
141
* A constant holding the positive infinity of type Decimal128.
142
*/
143
public static final Decimal128 POSITIVE_INFINITY;
144
145
/**
146
* A constant holding the negative infinity of type Decimal128.
147
*/
148
public static final Decimal128 NEGATIVE_INFINITY;
149
150
/**
151
* A constant holding a Not-a-Number (NaN) value of type Decimal128.
152
*/
153
public static final Decimal128 NaN;
154
155
/**
156
* A constant holding the positive zero value of type Decimal128.
157
*/
158
public static final Decimal128 POSITIVE_ZERO;
159
160
/**
161
* A constant holding the negative zero value of type Decimal128.
162
*/
163
public static final Decimal128 NEGATIVE_ZERO;
164
165
/**
166
* Create an instance from the given high and low order bits.
167
* @param high the high order 64 bits
168
* @param low the low order 64 bits
169
*/
170
public Decimal128(long high, long low);
171
172
/**
173
* Returns an instance representing the given long value.
174
* @param value the long value
175
* @return the Decimal128 instance
176
*/
177
public static Decimal128 fromIEEE754BIDEncoding(long high, long low);
178
179
/**
180
* Create a Decimal128 instance from a BigDecimal.
181
* @param value the BigDecimal value
182
* @return the Decimal128 instance
183
*/
184
public static Decimal128 parse(String value);
185
186
/**
187
* Create a Decimal128 instance from a BigDecimal.
188
* @param bigDecimalValue the BigDecimal value
189
* @return the Decimal128 instance
190
*/
191
public static Decimal128 valueOf(BigDecimal bigDecimalValue);
192
193
/**
194
* Create a Decimal128 instance from a long.
195
* @param longValue the long value
196
* @return the Decimal128 instance
197
*/
198
public static Decimal128 valueOf(long longValue);
199
200
/**
201
* Create a Decimal128 instance from a double.
202
* @param doubleValue the double value
203
* @return the Decimal128 instance
204
*/
205
public static Decimal128 valueOf(double doubleValue);
206
207
/**
208
* Create a Decimal128 instance from a string.
209
* @param value the string value
210
* @return the Decimal128 instance
211
*/
212
public static Decimal128 valueOf(String value);
213
214
/**
215
* Returns true if this Decimal128 is finite.
216
* @return true if finite
217
*/
218
public boolean isFinite();
219
220
/**
221
* Returns true if this Decimal128 is infinite.
222
* @return true if infinite
223
*/
224
public boolean isInfinite();
225
226
/**
227
* Returns true if this Decimal128 is Not-A-Number (NaN).
228
* @return true if NaN
229
*/
230
public boolean isNaN();
231
232
/**
233
* Returns true if this Decimal128 is negative.
234
* @return true if negative
235
*/
236
public boolean isNegative();
237
238
/**
239
* Gets the high order 64 bits.
240
* @return the high order 64 bits
241
*/
242
public long getHigh();
243
244
/**
245
* Gets the low order 64 bits.
246
* @return the low order 64 bits
247
*/
248
public long getLow();
249
250
/**
251
* Returns this Decimal128 as a BigDecimal.
252
* @return the BigDecimal representation
253
*/
254
public BigDecimal bigDecimalValue();
255
256
/**
257
* Returns this Decimal128 as a double.
258
* @return the double representation
259
*/
260
public double doubleValue();
261
262
public int compareTo(Decimal128 o);
263
public boolean equals(Object o);
264
public int hashCode();
265
public String toString();
266
}
267
```
268
269
## Binary Data Types
270
271
### BsonBinary
272
273
```java { .api }
274
public final class BsonBinary extends BsonValue {
275
/**
276
* Constructs a new instance.
277
* @param data the binary data
278
*/
279
public BsonBinary(byte[] data);
280
281
/**
282
* Constructs a new instance.
283
* @param type the binary sub type
284
* @param data the binary data
285
*/
286
public BsonBinary(BsonBinarySubType type, byte[] data);
287
288
/**
289
* Constructs a new instance with a UUID.
290
* @param uuid the UUID
291
*/
292
public BsonBinary(UUID uuid);
293
294
/**
295
* Constructs a new instance with a UUID and representation.
296
* @param uuid the UUID
297
* @param uuidRepresentation the UUID representation
298
*/
299
public BsonBinary(UUID uuid, UuidRepresentation uuidRepresentation);
300
301
/**
302
* Gets the type of this binary.
303
* @return the type
304
*/
305
public byte getType();
306
307
/**
308
* Gets the binary sub type.
309
* @return the binary sub type
310
*/
311
public BsonBinarySubType getBsonBinarySubType();
312
313
/**
314
* Gets the binary data.
315
* @return the binary data
316
*/
317
public byte[] getData();
318
319
/**
320
* Gets this binary as a UUID.
321
* @return the UUID
322
* @throws BsonInvalidOperationException if this binary is not a UUID
323
*/
324
public UUID asUuid();
325
326
/**
327
* Gets this binary as a UUID with the given representation.
328
* @param uuidRepresentation the UUID representation
329
* @return the UUID
330
*/
331
public UUID asUuid(UuidRepresentation uuidRepresentation);
332
}
333
```
334
335
### BsonBinarySubType
336
337
```java { .api }
338
public enum BsonBinarySubType {
339
/**
340
* Generic binary sub type.
341
*/
342
BINARY(0x00),
343
344
/**
345
* Function binary sub type.
346
*/
347
FUNCTION(0x01),
348
349
/**
350
* Old binary sub type.
351
*/
352
OLD_BINARY(0x02),
353
354
/**
355
* UUID old sub type.
356
*/
357
UUID_LEGACY(0x03),
358
359
/**
360
* UUID standard sub type.
361
*/
362
UUID_STANDARD(0x04),
363
364
/**
365
* MD5 sub type.
366
*/
367
MD5(0x05),
368
369
/**
370
* Encrypted sub type.
371
*/
372
ENCRYPTED(0x06),
373
374
/**
375
* Column sub type.
376
*/
377
COLUMN(0x07),
378
379
/**
380
* User defined sub type.
381
*/
382
USER_DEFINED(0x80);
383
384
/**
385
* Gets the value of this sub type.
386
* @return the value
387
*/
388
public byte getValue();
389
390
/**
391
* Returns true if the given value is a UUID sub type.
392
* @param value the value
393
* @return true if UUID sub type
394
*/
395
public static boolean isUuid(byte value);
396
}
397
```
398
399
## Timestamp Types
400
401
### BsonTimestamp
402
403
```java { .api }
404
public final class BsonTimestamp extends BsonValue implements Comparable<BsonTimestamp> {
405
/**
406
* Constructs a new instance.
407
* @param seconds the seconds since epoch
408
* @param increment the increment
409
*/
410
public BsonTimestamp(int seconds, int increment);
411
412
/**
413
* Constructs a new instance.
414
* @param value the combined timestamp value
415
*/
416
public BsonTimestamp(long value);
417
418
/**
419
* Gets the time in seconds since epoch.
420
* @return the time in seconds since epoch
421
*/
422
public int getTime();
423
424
/**
425
* Gets the increment.
426
* @return the increment
427
*/
428
public int getInc();
429
430
/**
431
* Gets the combined timestamp value.
432
* @return the combined timestamp value
433
*/
434
public long getValue();
435
436
public int compareTo(BsonTimestamp ts);
437
}
438
```
439
440
### BsonDateTime
441
442
```java { .api }
443
public final class BsonDateTime extends BsonValue implements Comparable<BsonDateTime> {
444
/**
445
* Constructs a new instance.
446
* @param value the date time value as milliseconds since epoch
447
*/
448
public BsonDateTime(long value);
449
450
/**
451
* Gets the DateTime value as milliseconds since epoch.
452
* @return the DateTime value
453
*/
454
public long getValue();
455
456
public int compareTo(BsonDateTime o);
457
}
458
```
459
460
## Regular Expressions
461
462
```java { .api }
463
public final class BsonRegularExpression extends BsonValue {
464
/**
465
* Constructs a new instance.
466
* @param pattern the pattern
467
*/
468
public BsonRegularExpression(String pattern);
469
470
/**
471
* Constructs a new instance.
472
* @param pattern the pattern
473
* @param options the options
474
*/
475
public BsonRegularExpression(String pattern, String options);
476
477
/**
478
* Gets the pattern.
479
* @return the pattern
480
*/
481
public String getPattern();
482
483
/**
484
* Gets the options.
485
* @return the options
486
*/
487
public String getOptions();
488
}
489
```
490
491
## JavaScript Types
492
493
### BsonJavaScript
494
495
```java { .api }
496
public final class BsonJavaScript extends BsonValue {
497
/**
498
* Constructs a new instance.
499
* @param code the JavaScript code
500
*/
501
public BsonJavaScript(String code);
502
503
/**
504
* Gets the JavaScript code.
505
* @return the code
506
*/
507
public String getCode();
508
}
509
```
510
511
### BsonJavaScriptWithScope
512
513
```java { .api }
514
public final class BsonJavaScriptWithScope extends BsonValue {
515
/**
516
* Constructs a new instance.
517
* @param code the JavaScript code
518
* @param scope the scope document
519
*/
520
public BsonJavaScriptWithScope(String code, BsonDocument scope);
521
522
/**
523
* Gets the JavaScript code.
524
* @return the code
525
*/
526
public String getCode();
527
528
/**
529
* Gets the scope document.
530
* @return the scope
531
*/
532
public BsonDocument getScope();
533
}
534
```
535
536
## Database Pointer (Deprecated)
537
538
```java { .api }
539
public final class BsonDbPointer extends BsonValue {
540
/**
541
* Constructs a new instance.
542
* @param namespace the namespace
543
* @param id the id
544
*/
545
public BsonDbPointer(String namespace, ObjectId id);
546
547
/**
548
* Gets the namespace.
549
* @return the namespace
550
*/
551
public String getNamespace();
552
553
/**
554
* Gets the id.
555
* @return the id
556
*/
557
public ObjectId getId();
558
}
559
```
560
561
## Symbol (Deprecated)
562
563
```java { .api }
564
public final class BsonSymbol extends BsonValue {
565
/**
566
* Constructs a new instance.
567
* @param symbol the symbol
568
*/
569
public BsonSymbol(String symbol);
570
571
/**
572
* Gets the symbol value.
573
* @return the symbol
574
*/
575
public String getSymbol();
576
}
577
```
578
579
## Binary Vector Types
580
581
### BinaryVector Interface
582
583
```java { .api }
584
public sealed interface BinaryVector permits Float32BinaryVector, Int8BinaryVector, PackedBitBinaryVector {
585
/**
586
* Returns the data type of the vector.
587
* @return the data type
588
*/
589
BsonBinarySubType getType();
590
591
/**
592
* Returns the binary representation of the vector.
593
* @return the binary data
594
*/
595
byte[] getData();
596
597
/**
598
* Returns the padding used for this vector.
599
* @return the padding
600
*/
601
byte getPadding();
602
}
603
```
604
605
### Float32BinaryVector
606
607
```java { .api }
608
public final class Float32BinaryVector implements BinaryVector {
609
/**
610
* Constructs a Float32BinaryVector.
611
* @param values the vector values
612
*/
613
public Float32BinaryVector(List<Float> values);
614
615
/**
616
* Gets the vector values.
617
* @return the vector values
618
*/
619
public List<Float> getValues();
620
621
public BsonBinarySubType getType();
622
public byte[] getData();
623
public byte getPadding();
624
}
625
```
626
627
### Int8BinaryVector
628
629
```java { .api }
630
public final class Int8BinaryVector implements BinaryVector {
631
/**
632
* Constructs an Int8BinaryVector.
633
* @param values the vector values
634
*/
635
public Int8BinaryVector(List<Byte> values);
636
637
/**
638
* Gets the vector values.
639
* @return the vector values
640
*/
641
public List<Byte> getValues();
642
643
public BsonBinarySubType getType();
644
public byte[] getData();
645
public byte getPadding();
646
}
647
```
648
649
### PackedBitBinaryVector
650
651
```java { .api }
652
public final class PackedBitBinaryVector implements BinaryVector {
653
/**
654
* Constructs a PackedBitBinaryVector.
655
* @param values the bit values (0 or 1)
656
* @param padding the padding for the last byte
657
*/
658
public PackedBitBinaryVector(List<Byte> values, byte padding);
659
660
/**
661
* Gets the bit values.
662
* @return the bit values
663
*/
664
public List<Byte> getValues();
665
666
public BsonBinarySubType getType();
667
public byte[] getData();
668
public byte getPadding();
669
}
670
```
671
672
## Code Types (Legacy)
673
674
### Code
675
676
```java { .api }
677
public class Code {
678
/**
679
* Constructs a new instance.
680
* @param code the code
681
*/
682
public Code(String code);
683
684
/**
685
* Gets the code.
686
* @return the code
687
*/
688
public String getCode();
689
690
public boolean equals(Object o);
691
public int hashCode();
692
public String toString();
693
}
694
```
695
696
### CodeWithScope
697
698
```java { .api }
699
public class CodeWithScope extends Code {
700
/**
701
* Constructs a new instance.
702
* @param code the code
703
* @param scope the scope
704
*/
705
public CodeWithScope(String code, Object scope);
706
707
/**
708
* Gets the scope.
709
* @return the scope
710
*/
711
public Object getScope();
712
713
public boolean equals(Object o);
714
public int hashCode();
715
public String toString();
716
}
717
```
718
719
## Usage Examples
720
721
### Working with ObjectId
722
723
```java
724
import org.bson.types.ObjectId;
725
import java.util.Date;
726
727
// Create ObjectIds
728
ObjectId id1 = new ObjectId(); // Current time
729
ObjectId id2 = new ObjectId("507f1f77bcf86cd799439011"); // From hex string
730
ObjectId id3 = new ObjectId(new Date()); // From specific date
731
732
// Extract information
733
Date creationTime = id1.getDate();
734
int timestamp = id1.getTimestamp(); // Seconds since epoch
735
String hex = id1.toHexString();
736
byte[] bytes = id1.toByteArray();
737
738
// Validate ObjectId strings
739
boolean valid = ObjectId.isValid("507f1f77bcf86cd799439011"); // true
740
boolean invalid = ObjectId.isValid("not-an-objectid"); // false
741
742
// Compare ObjectIds (chronological order)
743
ObjectId earlier = new ObjectId(new Date(System.currentTimeMillis() - 10000));
744
ObjectId later = new ObjectId();
745
int comparison = earlier.compareTo(later); // negative value
746
```
747
748
### High-Precision Decimal Operations
749
750
```java
751
import org.bson.types.Decimal128;
752
import java.math.BigDecimal;
753
754
// Create Decimal128 values
755
Decimal128 price = Decimal128.parse("99.99");
756
Decimal128 tax = Decimal128.valueOf(new BigDecimal("8.25"));
757
Decimal128 discount = Decimal128.valueOf(5.0);
758
759
// Convert to other types
760
BigDecimal priceBD = price.bigDecimalValue();
761
double priceDouble = price.doubleValue(); // May lose precision
762
763
// Check special values
764
Decimal128 infinity = Decimal128.POSITIVE_INFINITY;
765
Decimal128 nan = Decimal128.NaN;
766
boolean isFinite = price.isFinite(); // true
767
boolean isNegative = discount.isNegative(); // false
768
769
// Use in calculations (via BigDecimal)
770
BigDecimal total = priceBD.add(tax.bigDecimalValue()).subtract(discount.bigDecimalValue());
771
Decimal128 totalDecimal = Decimal128.valueOf(total);
772
```
773
774
### Binary Data Handling
775
776
```java
777
import org.bson.*;
778
import java.util.UUID;
779
780
// Generic binary data
781
byte[] imageData = loadImageBytes();
782
BsonBinary imageBinary = new BsonBinary(BsonBinarySubType.GENERIC, imageData);
783
784
// UUID handling
785
UUID uuid = UUID.randomUUID();
786
BsonBinary uuidBinary = new BsonBinary(uuid);
787
UUID retrievedUuid = uuidBinary.asUuid();
788
789
// Different UUID representations
790
BsonBinary javaLegacyUuid = new BsonBinary(uuid, UuidRepresentation.JAVA_LEGACY);
791
BsonBinary standardUuid = new BsonBinary(uuid, UuidRepresentation.STANDARD);
792
793
// Working with binary vectors
794
List<Float> vectorData = Arrays.asList(0.1f, 0.2f, 0.3f, 0.4f);
795
Float32BinaryVector vector = new Float32BinaryVector(vectorData);
796
BsonBinary vectorBinary = new BsonBinary(BsonBinarySubType.VECTOR, vector.getData());
797
```
798
799
### Timestamp Operations
800
801
```java
802
import org.bson.*;
803
804
// BSON Timestamp (MongoDB internal)
805
BsonTimestamp oplogTimestamp = new BsonTimestamp(1609459200, 1); // seconds, increment
806
int seconds = oplogTimestamp.getTime();
807
int increment = oplogTimestamp.getInc();
808
809
// BSON DateTime (standard date/time)
810
long currentMillis = System.currentTimeMillis();
811
BsonDateTime dateTime = new BsonDateTime(currentMillis);
812
long retrievedMillis = dateTime.getValue();
813
814
// Compare timestamps
815
BsonTimestamp ts1 = new BsonTimestamp(1609459200, 1);
816
BsonTimestamp ts2 = new BsonTimestamp(1609459200, 2);
817
int comparison = ts1.compareTo(ts2); // negative (ts1 is earlier)
818
```
819
820
### Regular Expressions
821
822
```java
823
import org.bson.BsonRegularExpression;
824
import java.util.regex.Pattern;
825
826
// Create BSON regular expressions
827
BsonRegularExpression regex1 = new BsonRegularExpression("^hello.*world$");
828
BsonRegularExpression regex2 = new BsonRegularExpression("email@domain", "i");
829
830
String pattern = regex1.getPattern(); // "^hello.*world$"
831
String options = regex1.getOptions(); // ""
832
String caseInsensitive = regex2.getOptions(); // "i"
833
834
// Use in documents
835
BsonDocument query = new BsonDocument("email", regex2);
836
```
837
838
### JavaScript Code Storage
839
840
```java
841
import org.bson.*;
842
843
// Simple JavaScript code
844
BsonJavaScript mapFunction = new BsonJavaScript(
845
"function() { emit(this.category, this.amount); }"
846
);
847
848
// JavaScript with scope
849
BsonDocument scope = new BsonDocument()
850
.append("multiplier", new BsonInt32(10))
851
.append("threshold", new BsonDouble(100.0));
852
853
BsonJavaScriptWithScope reduceFunction = new BsonJavaScriptWithScope(
854
"function(key, values) { return Array.sum(values) * multiplier; }",
855
scope
856
);
857
858
String code = reduceFunction.getCode();
859
BsonDocument retrievedScope = reduceFunction.getScope();
860
```