BSON es el formato binario de documentos de MongoDB, con prefijo de longitud. Este convertidor procesa un documento BSON como Extended JSON v2 canónico y conserva valores ObjectId, Date, Binary, expresiones regulares, Timestamp, Decimal128, Int32 y Long de 64 bits.
Usa BSON para documentos MongoDB o payloads de drivers cuyos consumidores admitan los mismos tipos BSON y Extended JSON. Extended JSON canónico no es JSON simple: conserva los envoltorios $oid, $date, $binary, $regularExpression, $timestamp, $numberDecimal y $numberLong; este convertidor no decodifica mensajes del protocolo de red de MongoDB.
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