Skip to content

BSON

Query BSON documents and move them between files and tables

Connector software
Free and open source
Service credentials
Not needed
Use with an agent

Install the Orchard skill in your project to help your agent find connectors, configure them, and verify SQL results.

npx skills add Query-farm/vgi-skills --skill orchard

Copy this request into your coding agent to get started.

Use https://query.farm/products/orchard/connectors/bson/index.md to help me query BSON with DuckDB or Haybarn 2.0.1 and VGI protocol 3.4. Ask only for missing details about the result I need or whether I want local execution, self-hosting or Query Farm hosting. Check the connector's actual hosting availability, credentials and input requirements. Read one format of each needed reference and the exact object declarations before writing SQL. Use a released connector, and distinguish a saved example result from anything you actually execute. If you cannot run the query, tell me what remains to verify.

Fan a concatenated BSON stream into one row per document with its byte length.

Example output · captured
Connector release
v0.6.0
Engine
2.0.1
VGI protocol
3.4.0
SELECT idx, octet_length(doc) AS n
FROM bson.main.bson_seq(from_hex('05000000000500000000'))
ORDER BY idx
Result
idx n
0 5
1 5

Quick start

Choose where to run BSON, then follow the steps below.

The connector runs alongside DuckDB or Haybarn. No Query Farm account is needed.

1. Install the vgi extension

Run this in your SQL client. On DuckDB, keep FROM query_farm on LOAD in later sessions.

setup.sql
SET allow_extension_repositories = 'allowed';

CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
    WITH PREFIX 'https://duckdb-extensions.query.farm';

INSTALL vgi FROM query_farm;
LOAD vgi FROM query_farm;

2. Attach the connector

Attach the release directly

Downloads the latest release for your platform and caches it locally.

ATTACH 'bson' AS bson (
  TYPE vgi,
  LOCATION 'github-auto://Query-farm/vgi-bson'
);

3. Run a query

query.sql
SELECT idx, octet_length(doc) AS n
FROM bson.main.bson_seq(from_hex('05000000000500000000'))
ORDER BY idx
More example queries →
Technical details
Verified connector release
v0.6.0
Engine
2.0.1
VGI protocol
3.4.0
Verified on
December 1, 2026
Release notes on GitHub
Pin a version for production

When running the connector yourself, keep a specific release until you’re ready to upgrade. Replace the ATTACH statement above with this one and follow the same extension and credential setup.

Attach the release directly

Uses the verified release each time you attach the connector.

ATTACH 'bson' AS bson (
  TYPE vgi,
  LOCATION 'github-auto://Query-farm/[email protected]'
);

Overview

BSON (Binary JSON) decode & encode plus Extended JSON v2, typed field extraction, mongodump/oplog/GridFS stream splitting, and raw BSON COPY import/export for SQL.

Catalog

Everything bson exposes once attached — read straight from the worker's released build.

bson 1 schema
main 1 view · 16 functions

BSON decode / encode, Extended JSON v2, typed field extraction, and mongodump/oplog/GridFS stream splitting, and raw BSON COPY import/export.

Schema examples (11)
Examples (11)

Render a BSON document as canonical (lossless) Extended JSON v2.

SELECT bson.main.to_json(bson.main.from_json('{"a":1}'));

Render the same document as relaxed, human-readable Extended JSON.

SELECT bson.main.to_json(bson.main.from_json('{"a":1}'), 'relaxed');

Extract a nested leaf by dotted path without decoding the whole document.

SELECT bson.main.field(bson.main.from_json('{"o":{"sku":"abc"}}'), 'o.sku');

Check that a tiny empty document is structurally well-formed.

SELECT (bson.main.well_formed(from_hex('0500000000'))).ok;
7 more examples

Report the top-level BSON type name of a document.

SELECT bson.main.type_of(bson.main.from_json('{"a":1}'));

Fan a concatenated BSON stream into one row per document with its byte length.

SELECT idx, octet_length(doc) AS n
FROM bson.main.bson_seq(from_hex('05000000000500000000'))
ORDER BY idx;
Result
idx n
0 5
1 5

Audit which BSON type every document's _id uses in a mongodump file body (three documents, inlined as hex and split with bson_seq), looking up its one-byte type code and Extended JSON wrapper in the bson_types registry.

SELECT t.type_name, t.type_byte, t.extjson_wrapper, count(*) AS docs
FROM bson.main.bson_seq(from_hex('2f000000075f69640054759eb3c090d83494e2d804026e616d650006000000616c6963650010616765001e000000002d000000075f69640054759eb3c090d83494e2d805026e616d650004000000626f6200106167650019000000002f000000075f69640054759eb3c090d83494e2d806026e616d6500060000006361726f6c0010616765002900000000')) AS d
JOIN bson.main.bson_types AS t ON t.type_name = bson.main.type_of(d.doc, '_id')
GROUP BY t.type_name, t.type_byte, t.extjson_wrapper
ORDER BY docs DESC, t.type_name;

Recover when each document in a mongodump file body (three documents, inlined as hex and split with bson_seq) was created from the timestamp embedded in its ObjectId _id, next to the document as relaxed Extended JSON.

SELECT d.idx,
  bson.main.objectid_timestamp(bson.main.field(d.doc, '_id', 'objectid')) AS created,
  bson.main.to_json(d.doc, 'relaxed') AS doc_json
FROM bson.main.bson_seq(from_hex('2f000000075f69640054759eb3c090d83494e2d804026e616d650006000000616c6963650010616765001e000000002d000000075f69640054759eb3c090d83494e2d805026e616d650004000000626f6200106167650019000000002f000000075f69640054759eb3c090d83494e2d806026e616d6500060000006361726f6c0010616765002900000000')) AS d
ORDER BY d.idx;

Split a concatenated oplog-style BSON stream into documents and count the entries per operation type (i = insert, u = update).

SELECT bson.main.field(s.doc, 'op') AS op, count(*) AS entries
FROM bson.main.bson_seq(bson.main.from_json('{"op":"i","ns":"shop.orders"}') || bson.main.from_json('{"op":"u","ns":"shop.orders"}') || bson.main.from_json('{"op":"i","ns":"shop.users"}')) AS s
GROUP BY op
ORDER BY op;

Canonical Extended JSON round-trips BSON byte-for-byte (the migration guarantee).

SELECT bson.main.from_json(bson.main.to_json(bson.main.from_json('{"a":1}'))) = bson.main.from_json('{"a":1}') AS roundtrips;

A minimal empty document (05 00 00 00 00) is well-formed.

SELECT (bson.main.well_formed(from_hex('0500000000'))).ok AS ok;
Views
bson_types 2 examples5 cols

The BSON element-type registry: every BSON type, its one-byte type code, and its canonical Extended JSON v2 wrapper.

Columns
type_name VARCHAR
The BSON type name as reported by `type_of`, e.g. 'objectId', 'decimal128', 'timestamp'.
type_byte VARCHAR
The one-byte BSON element type code, as a 0x?? hex string (0x01–0x13, plus 0xFF minKey and 0x7F maxKey).
type_class VARCHAR
A coarse grouping for browsing: numeric, text, document, binary, temporal, identifier, code, scalar, sentinel, or deprecated.
extjson_wrapper VARCHAR
The canonical Extended JSON v2 shape a value of this type serializes to (… marks the value slot).
notes VARCHAR
A one-line semantic note, including the Timestamp-vs-UTCDateTime and deprecated-type caveats.
Examples (2)

List the temporal BSON types and their Extended JSON wrappers.

SELECT type_name, type_byte, extjson_wrapper
FROM bson.main.bson_types
WHERE type_class = 'temporal'
ORDER BY type_name;

Audit which BSON type every document's _id uses in a mongodump file body (three documents, inlined as hex and split with bson_seq), looking up its one-byte type code and Extended JSON wrapper in the bson_types registry.

SELECT t.type_name, t.type_byte, t.extjson_wrapper, count(*) AS docs
FROM bson.main.bson_seq(from_hex('2f000000075f69640054759eb3c090d83494e2d804026e616d650006000000616c6963650010616765001e000000002d000000075f69640054759eb3c090d83494e2d805026e616d650004000000626f6200106167650019000000002f000000075f69640054759eb3c090d83494e2d806026e616d6500060000006361726f6c0010616765002900000000')) AS d
JOIN bson.main.bson_types AS t ON t.type_name = bson.main.type_of(d.doc, '_id')
GROUP BY t.type_name, t.type_byte, t.extjson_wrapper
ORDER BY docs DESC, t.type_name;
Link
Scalar functions
decode (doc ANY, mode VARCHAR) +1 overload 1 example

Decode a BSON document to its richest form (Extended JSON in v1)

Arguments
doc ANY
A BSON-encoded BLOB to decode.
mode VARCHAR
Which self-describing form to target when decoding. All modes currently materialize as canonical Extended JSON text (see the function note), because a DuckDB scalar fixes its output column type at bind time. · default "auto"
Overloads
decode(doc ANY) → VARCHARdecode(doc ANY, mode VARCHAR) → VARCHAR
ReturnsVARCHAR
Example

Decode forcing JSON mode.

SELECT bson.main.decode(bson.main.from_json('{"a":1}'), 'json') AS d;
Link
encode (value ANY) 1 example

Encode a DuckDB STRUCT/MAP value as a BSON document

Arguments
value ANY
The DuckDB value to encode as a BSON document. Must be a STRUCT or MAP at the top level (BSON documents have no top-level scalar).
ReturnsBLOB
Example

Encode a struct to BSON and hex it.

SELECT to_hex(bson.main.encode({'a': 1, 'b': 'x'})) AS h;
Link
field (doc ANY, path VARCHAR, as VARCHAR) +1 overload 1 example

Extract a BSON field by dotted path (inferred leaf rendering)

Arguments
doc ANY
A BSON-encoded BLOB to extract from.
path VARCHAR
A dotted field path; address array elements by their zero-based position, e.g. 'o._id' or 'items.0.sku'.
as VARCHAR
How to coerce the extracted leaf into a cast-ready string. Omit (or NULL) to infer the rendering from the leaf; see the function description for what each mode emits and the SQL type to cast the result to.
Overloads
field(doc ANY, path VARCHAR) → VARCHARfield(doc ANY, path VARCHAR, as VARCHAR) → VARCHAR
ReturnsVARCHAR
Example

Extract _id as a hex ObjectId.

SELECT bson.main.field(bson.main.from_json('{"_id":{"$oid":"54759eb3c090d83494e2d804"}}'), '_id', 'objectid') AS id;
Link
from_json (extjson ANY) 1 example

Encode an Extended JSON v2 string as BSON document bytes

Arguments
extjson ANY
MongoDB Extended JSON v2 text (canonical or relaxed) to encode as a BSON document.
ReturnsBLOB
Example

Encode a JSON document to BSON and hex it.

SELECT to_hex(bson.main.from_json('{"a":1}')) AS h;
Link
is_valid (doc ANY) 1 example

Return true iff the blob is exactly one well-formed BSON document

Arguments
doc ANY
A BLOB to test for BSON well-formedness.
ReturnsBOOLEAN
Example

Validate a tiny empty BSON document (05 00 00 00 00).

SELECT bson.main.is_valid(from_hex('0500000000')) AS ok;
Link
keys (doc ANY) 1 example

List the top-level field names of a BSON document in document order

Arguments
doc ANY
A BSON-encoded BLOB whose top-level field names to list.
ReturnsVARCHAR[]
Example

List the keys of a {a:1,b:2} document.

SELECT bson.main.keys(bson.main.from_json('{"a":1,"b":2}')) AS k;
Link
objectid_from_hex (hex VARCHAR) 1 example

Convert a 24-char hex ObjectId string to its 12-byte BLOB

Arguments
hex VARCHAR
A 24-char hexadecimal ObjectId string.
ReturnsBLOB
Example

12-byte ObjectId from hex.

SELECT to_hex(bson.main.objectid_from_hex('54759eb3c090d83494e2d804')) AS b;
Link
objectid_hex (oid ANY) 1 example

Convert a 12-byte ObjectId BLOB to its 24-char hex string

Arguments
oid ANY
A 12-byte ObjectId BLOB.
ReturnsVARCHAR
Example

Hex of a 12-byte ObjectId.

SELECT bson.main.objectid_hex(bson.main.objectid_from_hex('54759eb3c090d83494e2d804')) AS h;
Link
objectid_timestamp (oid ANY) 1 example

Return the creation time embedded in an ObjectId (TIMESTAMPTZ)

Arguments
oid ANY
An ObjectId, given either as its 24-character hexadecimal string or as its 12 raw bytes.
ReturnsTIMESTAMP WITH TIME ZONE
Example

Creation time of an ObjectId.

SELECT bson.main.objectid_timestamp('54759eb3c090d83494e2d804') AS created;
Link
timestamp_parts (ts ANY) 1 example

Return the raw (time, increment) pair of a BSON Timestamp as STRUCT(t,i)

Arguments
ts ANY
A BSON internal replication-clock value in its decoded (t, i) form — the (seconds, increment) pair.
ReturnsSTRUCT(t UINTEGER, i UINTEGER)
Example

Read the (t, i) parts of a Timestamp.

SELECT (bson.main.timestamp_parts({'t': 1416994483, 'i': 2})).i AS inc;
Link
timestamp_to_ts (ts ANY) 1 example

Convert a BSON Timestamp STRUCT(t,i) to a TIMESTAMPTZ (from t)

Arguments
ts ANY
A BSON internal replication-clock value in its decoded (t, i) form — the (seconds, increment) pair.
ReturnsTIMESTAMP WITH TIME ZONE
Example

Convert a Timestamp struct to a TIMESTAMPTZ.

SELECT bson.main.timestamp_to_ts({'t': 1416994483, 'i': 1}) AS ts;
Link
to_json (doc ANY, mode VARCHAR) +1 overload 1 example

Render a BSON document as canonical Extended JSON v2

Arguments
doc ANY
A BSON-encoded BLOB to render as Extended JSON.
mode VARCHAR
Extended JSON mode. 'canonical' (the default) is the type-preserving lossless form; 'relaxed' renders in-range numbers and dates natively for readability. · default "canonical"
Overloads
to_json(doc ANY) → VARCHARto_json(doc ANY, mode VARCHAR) → VARCHAR
ReturnsVARCHAR
Example

Relaxed Extended JSON of {a:1}.

SELECT bson.main.to_json(bson.main.from_json('{"a":1}'), 'relaxed') AS j;
Link
type_of (doc ANY, path VARCHAR) +1 overload 1 example

Return the top-level BSON type name of a document

Arguments
doc ANY
A BSON-encoded BLOB to inspect.
path VARCHAR
A dotted field path (e.g. 'o._id'); omit for the top-level document type.
Overloads
type_of(doc ANY) → VARCHARtype_of(doc ANY, path VARCHAR) → VARCHAR
ReturnsVARCHAR
Example

Type of a nested ObjectId field.

SELECT bson.main.type_of(bson.main.from_json('{"_id":{"$oid":"54759eb3c090d83494e2d804"}}'), '_id') AS t;
Link
well_formed (doc ANY) 1 example

Diagnose BSON well-formedness: STRUCT(ok BOOL, error VARCHAR, kind VARCHAR)

Arguments
doc ANY
A BLOB to diagnose for BSON well-formedness.
ReturnsSTRUCT(ok BOOLEAN, "error" VARCHAR, kind VARCHAR)
Example

Diagnose a truncated document.

SELECT (bson.main.well_formed(from_hex('0500000001'))).kind AS kind;
Link
Table functions
bson_seq (stream BLOB) 4 examples

Split a concatenated length-prefixed BSON stream into one row per document

Arguments
stream BLOB
N concatenated length-prefixed BSON documents — the wire body of a mongodump `.bson` file, an oplog batch, or a GridFS reassembly.
Returns columns
idx BIGINT
Zero-based position of the document within the concatenated stream.
doc BLOB
The raw bytes of one framed BSON document, ready to feed to decode / to_json / field.
Examples (4)

Split two concatenated empty documents.

SELECT idx, octet_length(doc) AS n
FROM bson.main.bson_seq(from_hex('05000000000500000000'))
ORDER BY idx;
Result
idx n
0 5
1 5

Split a concatenated oplog-style BSON stream into documents and count the entries per operation type (i = insert, u = update).

SELECT bson.main.field(s.doc, 'op') AS op, count(*) AS entries
FROM bson.main.bson_seq(bson.main.from_json('{"op":"i","ns":"shop.orders"}') || bson.main.from_json('{"op":"u","ns":"shop.orders"}') || bson.main.from_json('{"op":"i","ns":"shop.users"}')) AS s
GROUP BY op
ORDER BY op;

Recover when each document in a mongodump file body (three documents, inlined as hex and split with bson_seq) was created from the timestamp embedded in its ObjectId _id, next to the document as relaxed Extended JSON.

SELECT d.idx,
  bson.main.objectid_timestamp(bson.main.field(d.doc, '_id', 'objectid')) AS created,
  bson.main.to_json(d.doc, 'relaxed') AS doc_json
FROM bson.main.bson_seq(from_hex('2f000000075f69640054759eb3c090d83494e2d804026e616d650006000000616c6963650010616765001e000000002d000000075f69640054759eb3c090d83494e2d805026e616d650004000000626f6200106167650019000000002f000000075f69640054759eb3c090d83494e2d806026e616d6500060000006361726f6c0010616765002900000000')) AS d
ORDER BY d.idx;
1 more example

Audit which BSON type every document's _id uses in a mongodump file body (three documents, inlined as hex and split with bson_seq), looking up its one-byte type code and Extended JSON wrapper in the bson_types registry.

SELECT t.type_name, t.type_byte, t.extjson_wrapper, count(*) AS docs
FROM bson.main.bson_seq(from_hex('2f000000075f69640054759eb3c090d83494e2d804026e616d650006000000616c6963650010616765001e000000002d000000075f69640054759eb3c090d83494e2d805026e616d650004000000626f6200106167650019000000002f000000075f69640054759eb3c090d83494e2d806026e616d6500060000006361726f6c0010616765002900000000')) AS d
JOIN bson.main.bson_types AS t ON t.type_name = bson.main.type_of(d.doc, '_id')
GROUP BY t.type_name, t.type_byte, t.extjson_wrapper
ORDER BY docs DESC, t.type_name;
Link
mongodump_read (glob VARCHAR) 1 example

Read a glob of mongodump .bson files into one row per document

Arguments
glob VARCHAR
A local-filesystem glob of `.bson` files, e.g. '/backups/mydb/*.bson'.
Returns columns
idx BIGINT
Zero-based position of the document within its own source file.
doc BLOB
The raw bytes of one framed BSON document, ready to feed to decode / to_json / field.
file VARCHAR
Path of the source .bson file the document was read from.
Example
COPY (SELECT bson.main.from_json(j) AS doc FROM (VALUES (1, '{"name":"alice","age":30}'), (2, '{"name":"bob","age":25}'), (3, '{"name":"carol","age":41}')) AS v(n, j) ORDER BY n) TO '/tmp/vgi_bson_example.bson' (FORMAT 'bson.bson');
SELECT idx, bson.main.to_json(doc, 'relaxed') AS doc_json FROM bson.main.mongodump_read('/tmp/vgi_bson_example.bson') ORDER BY idx;
Link

COPY formats

Attaching bson also registers a file format for DuckDB's own COPY statement, so you can load files into local tables and write query results out to files without a function call. The FORMAT name starts with the ATTACH alias — bson with the Quick start above; use yours if you attach it under another name.

FORMAT 'bson.bson'

COPY … FROM · import COPY … TO · export

BSON COPY. Byte-preserving BSON file import and export

copy.sql
-- Load a file into an existing local table
COPY my_table FROM 'data.bson' (FORMAT 'bson.bson');

-- Write a query's rows out to a file
COPY (SELECT * FROM my_table) TO 'out.bson' (FORMAT 'bson.bson');

Options

Pass these inside the COPY statement's parentheses, after FORMAT. Unknown options are rejected.

modeVARCHAR
Document representation: 'raw' (default), exactly one BLOB column.
max_document_sizeBIGINT
Maximum bytes per BSON document, including its prefix; default 16 MiB. Applies to import and export.
Full reference

Import or export raw BSON documents using COPY with FORMAT 'bson.bson' (replace the first bson with your attached catalog name). Requires exactly one BLOB column, one complete BSON document per row. MODE defaults to 'raw'; typed rows are not supported. Local files only; reads stream in bounded batches. Invalid documents, duplicate keys, truncated files, NULL rows, and oversized documents fail the COPY. MAX_DOCUMENT_SIZE defaults to 16777216 bytes (16 MiB), and may be raised up to 2147483647. Bytes are preserved without decoding/re-encoding. Export preserves source order (use ORDER BY for deterministic ordering), stages batches in shared storage, and atomically replaces the destination only after successful writing. Empty export creates a zero-byte file.

Import and export

Create the destination table in a writable DuckDB schema, then import a local mongodump document file. Qualify the format by the catalog's ATTACH alias.

COPY <target_table> FROM '<input_path>' (FORMAT '<catalog>.bson');
COPY (<query_returning_one_blob_column>) TO '<output_path>'
(FORMAT '<catalog>.bson', MODE 'raw');

A bad import aborts the statement and reports its filename and document byte offset. A bad export reports its source row and leaves an existing destination intact. COPY accepts one uncompressed file; cloud paths, globs, collection metadata and mongodump archive containers are outside this format. Paths are resolved on the worker's filesystem. MAX_DOCUMENT_SIZE can be raised explicitly for larger documents.

Try these queries

Render a BSON document as canonical (lossless) Extended JSON v2.

SELECT bson.main.to_json(bson.main.from_json('{"a":1}'))

Uses to_jsonfrom_json

Extract a nested leaf by dotted path without decoding the whole document.

SELECT bson.main.field(bson.main.from_json('{"o":{"sku":"abc"}}'), 'o.sku')

Uses fieldfrom_json

Check that a tiny empty document is structurally well-formed.

SELECT (bson.main.well_formed(from_hex('0500000000'))).ok

Uses well_formed

Report the top-level BSON type name of a document.

SELECT bson.main.type_of(bson.main.from_json('{"a":1}'))

Uses type_offrom_json

Audit which BSON type every document's _id uses in a mongodump file body (three documents, inlined as hex and split with bson_seq), looking up its one-byte type code and Extended JSON wrapper in the bson_types registry.

SELECT t.type_name, t.type_byte, t.extjson_wrapper, count(*) AS docs
FROM bson.main.bson_seq(from_hex('2f000000075f69640054759eb3c090d83494e2d804026e616d650006000000616c6963650010616765001e000000002d000000075f69640054759eb3c090d83494e2d805026e616d650004000000626f6200106167650019000000002f000000075f69640054759eb3c090d83494e2d806026e616d6500060000006361726f6c0010616765002900000000')) AS d
JOIN bson.main.bson_types AS t ON t.type_name = bson.main.type_of(d.doc, '_id')
GROUP BY t.type_name, t.type_byte, t.extjson_wrapper
ORDER BY docs DESC, t.type_name

Uses bson_seqbson_typestype_of

Recover when each document in a mongodump file body (three documents, inlined as hex and split with bson_seq) was created from the timestamp embedded in its ObjectId _id, next to the document as relaxed Extended JSON.

SELECT d.idx,
  bson.main.objectid_timestamp(bson.main.field(d.doc, '_id', 'objectid')) AS created,
  bson.main.to_json(d.doc, 'relaxed') AS doc_json
FROM bson.main.bson_seq(from_hex('2f000000075f69640054759eb3c090d83494e2d804026e616d650006000000616c6963650010616765001e000000002d000000075f69640054759eb3c090d83494e2d805026e616d650004000000626f6200106167650019000000002f000000075f69640054759eb3c090d83494e2d806026e616d6500060000006361726f6c0010616765002900000000')) AS d
ORDER BY d.idx

Uses objectid_timestampfieldto_jsonbson_seq

20 more examples in the Catalog, each listed under the table or function it uses.

Questions it can answer

Plain-English questions from the worker's agent test tasks. An AI agent with this catalog attached should answer each one with SQL.

  • Using the bson worker, return the creation time embedded in the ObjectId whose hexadecimal string is 54759eb3c090d83494e2d804.
  • Using the bson worker, encode the DuckDB struct {'a': 1} to BSON bytes with the encode function and return the result as an uppercase hexadecimal string.
  • Using the bson worker, read the increment (i) component from the BSON internal Timestamp struct {'t': 1416994483, 'i': 7} using timestamp_parts.
  • Using the bson worker, convert the BSON internal Timestamp struct {'t': 1416994483, 'i': 7} to a TIMESTAMPTZ from its seconds component using timestamp_to_ts.

BSON is an independent open-source connector from Query.Farm. It is not affiliated with, endorsed by or sponsored by the services, projects or organisations it works with. Product names, logos and trademarks belong to their respective owners.