BSON 转 Extended JSON

关于 BSON

什么是 BSON?

BSON 是 MongoDB 的二进制文档序列化格式。它保存 JSON 形态的文档,并支持 ObjectId、日期、二进制数据、正则表达式、时间戳和 64 位整数等类型值。

什么时候使用 BSON?

当需要查看 MongoDB 文档、测试驱动载荷、调试 Extended JSON,或在已经使用 MongoDB BSON 模型的系统之间移动带类型的文档数据时,可以使用 BSON。

JavaScript 中的 BSON

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));
				

Go 中的 BSON

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 中的 BSON

<?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