BSON is MongoDB's binary document serialization format. It stores JSON-shaped documents with typed values such as ObjectId, dates, binary data, regular expressions, timestamps, and 64-bit integers.
Use BSON when inspecting MongoDB documents, testing driver payloads, debugging Extended JSON, or moving typed document data between systems that already use MongoDB's BSON model.
import { deserialize, EJSON, serialize } from 'bson';
const value = EJSON.deserialize({ hello: 'world' });
const bytes = serialize(value);
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
console.log(hex);
// Output: 160000000268656c6c6f0006000000776f726c640000
console.log(EJSON.stringify(deserialize(bytes), { relaxed: false }, 2));
package main
import (
"fmt"
"go.mongodb.org/mongo-driver/bson"
)
func main() {
value := bson.D{{Key: "hello", Value: "world"}}
encoded, _ := bson.Marshal(value)
fmt.Printf("%x\n", encoded)
// Output: 160000000268656c6c6f0006000000776f726c640000
var decoded bson.M
_ = bson.Unmarshal(encoded, &decoded)
fmt.Println(decoded["hello"])
// Output: world
}
<?php
$value = ['hello' => 'world'];
$encoded = MongoDB\BSON\fromPHP($value);
echo bin2hex($encoded) . PHP_EOL;
// Output: 160000000268656c6c6f0006000000776f726c640000
$decoded = MongoDB\BSON\toPHP($encoded);
echo $decoded->hello . PHP_EOL;
// Output: world