Skip to content

Commit a4f6790

Browse files
authored
DOCSP-48390 Document Data Formats: EJSON (#1069)
* DOCSP-48390 Document Data Formats: EJSON * add to toc and bson import note * edit * add binary type * edit ouputs * remove additional info section * last small edits * fix link * edit * tech review * edits * tech review 2 * add note about bad orange highlighting * tech review
1 parent dc5e924 commit a4f6790

File tree

3 files changed

+236
-6
lines changed

3 files changed

+236
-6
lines changed

source/data-formats.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ Specialized Data Formats
2222
:maxdepth: 1
2323

2424
BSON </data-formats/bson>
25+
Extended JSON <data-formats/extended-json>
2526
Time Series Data </data-formats/time-series>
2627

2728
Overview

source/data-formats/bson.txt

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
.. _node-bson-control:
22
.. _node-bson:
33

4-
==============
5-
Work with BSON
6-
==============
4+
===================
5+
Work with BSON Data
6+
===================
77

88
.. default-domain:: mongodb
99

@@ -37,6 +37,16 @@ The code samples in this guide use the following BSON document as an example:
3737
"name" : "Mongo's Pizza"
3838
}
3939

40+
.. note:: Use the {+driver-short+}'s BSON package
41+
42+
We recommend that you use the BSON package that is bundled with the driver to avoid
43+
compatibility issues with other BSON packages. You can import the {+driver-short+}'s
44+
BSON package with the following import statement:
45+
46+
.. code-block:: js
47+
48+
import { BSON } from 'mongodb';
49+
4050
BSON Data Types
4151
---------------
4252

@@ -56,7 +66,7 @@ example generates a random UUID:
5666

5767
import { UUID } from 'mongodb';
5868

59-
const myUuid = new BSON.UUID();
69+
const myUuid = new UUID();
6070

6171
Create a BSON Document
6272
----------------------
@@ -109,7 +119,7 @@ The following example writes the sample BSON document to ``file.bson``:
109119
.. code-block:: javascript
110120

111121
import fs from 'fs/promises'; // Import the file system module
112-
import { BSON } from 'bson'; // Import the BSON package
122+
import { BSON } from 'mongodb'; // Import the BSON package
113123

114124
// Create a BSON object
115125
const bsonData = BSON.serialize(result);
@@ -133,7 +143,7 @@ The following example reads the sample BSON document from ``file.bson``:
133143
:language: javascript
134144

135145
import fs from 'fs/promises'; // Import the file system module
136-
import { BSON } from 'bson'; // Import the BSON package
146+
import { BSON } from 'mongodb'; // Import the BSON package
137147

138148
// Read the BSON data from a file
139149
const data = await fs.readFile('file.bson');

source/data-formats/extended-json.txt

Lines changed: 219 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,219 @@
1+
.. _node-extended-json:
2+
3+
============================
4+
Work with Extended JSON Data
5+
============================
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:keywords: code examples, bson, relaxed, canonical, legacy
19+
20+
Overview
21+
--------
22+
23+
JSON is a data format that represents the values of objects, arrays, numbers,
24+
strings, booleans, and nulls. The **Extended JSON** format defines a reserved
25+
set of keys prefixed with "``$``" to represent field type information that
26+
directly corresponds to each type in BSON, the format that MongoDB uses to
27+
store data.
28+
29+
Extended JSON Formats
30+
---------------------
31+
32+
MongoDB Extended JSON features different string formats to represent BSON data.
33+
Each of the different formats conform to the JSON RFC
34+
and meet specific use cases. The **Extended** format, also known as the
35+
**Canonical** format, features specific representations for every BSON type
36+
for bidirectional conversion without loss of information. The **Relaxed Mode**
37+
format is more concise and closer to ordinary JSON, but does not represent
38+
all the type information such as the specific bit width of numeric fields.
39+
40+
See the following table to see a description of each format:
41+
42+
.. list-table::
43+
:header-rows: 1
44+
:stub-columns: 1
45+
:widths: 10 40
46+
47+
* - Name
48+
- Description
49+
50+
* - **Extended**
51+
- | Also known as the *Canonical* format, this JSON representation avoids loss of
52+
BSON type information.
53+
| This format prioritizes type preservation at the loss of human-readability and
54+
interoperability with older formats.
55+
56+
* - **Relaxed Mode**
57+
- | JSON representation that describes BSON documents with some type information loss.
58+
| This format prioritizes human-readability and interoperability at the loss of
59+
certain type information.
60+
61+
To learn more about JSON, BSON, and Extended JSON, see
62+
`our article about JSON and BSON <https://www.mongodb.com/resources/basics/json-and-bson>`__
63+
and :manual:`Extended JSON </reference/mongodb-extended-json/>` in the {+mdb-server+} manual.
64+
65+
.. _extended_json_example_section:
66+
67+
Extended JSON Examples
68+
~~~~~~~~~~~~~~~~~~~~~~
69+
70+
The following examples show a document containing an ObjectId, date, and long
71+
number field represented in the Extended JSON format. Click the tab that
72+
corresponds to the format of the example you want to see:
73+
74+
.. tabs::
75+
76+
.. tab:: Extended
77+
:tabid: extended-format
78+
79+
.. code-block:: json
80+
81+
{
82+
"_id": { "$oid": "573a1391f29313caabcd9637" },
83+
"createdAt": { "$date": { "$numberLong": "1601499609" }},
84+
"numViews": { "$numberLong": "36520312" }
85+
}
86+
87+
.. tab:: Relaxed Mode
88+
:tabid: relaxed-mode-format
89+
90+
.. code-block:: json
91+
92+
{
93+
"_id": { "$oid": "573a1391f29313caabcd9637" },
94+
"createdAt": { "$date": "2020-09-30T18:22:51.648Z" },
95+
"numViews": 36520312
96+
}
97+
98+
Write Extended JSON
99+
-------------------
100+
101+
You can write an Extended JSON string from a BSON document object by using the
102+
``EJSON.stringify()`` method.
103+
104+
The following example outputs an Extended JSON string in the Relaxed format:
105+
106+
.. io-code-block::
107+
108+
.. input::
109+
:language: js
110+
111+
import { Code, BSON } from 'mongodb';
112+
const EJSON = BSON.EJSON;
113+
114+
const doc = {
115+
foo: [1, 2],
116+
bar: { hello: "world" },
117+
code: new Code("function x() { return 1; }", {}),
118+
date: new Date(2024, 6, 20, 10, 30, 0),
119+
};
120+
121+
const ejsonStr = EJSON.stringify(doc);
122+
console.log(ejsonStr);
123+
124+
.. output::
125+
:language: none
126+
:visible: false
127+
128+
{"foo":[1,2],"bar":{"hello":"world"},"code":{"$code":"function x() { return 1; }","$scope":{}},"date":{"$date":"2024-07-20T14:30:00Z"}}
129+
130+
By default, the ``stringify()`` method returns the Extended JSON string in the
131+
Relaxed format. To specify the Canonical format, set the ``relaxed``
132+
option to ``false``.
133+
134+
The following example shows how to output Extended JSON in the Canonical format:
135+
136+
.. io-code-block::
137+
138+
.. input::
139+
:language: js
140+
141+
import { Code, BSON } from 'mongodb';
142+
const EJSON = BSON.EJSON;
143+
144+
const doc = {
145+
foo: [1, 2],
146+
bar: { hello: "world" },
147+
code: new Code("function x() { return 1; }", {}),
148+
date: new Date(2024, 6, 20, 10, 30, 0),
149+
};
150+
151+
const ejsonStr = EJSON.stringify(doc, { relaxed: false });
152+
print(ejsonStr)
153+
154+
.. output::
155+
:language: none
156+
:visible: false
157+
158+
{"foo":[{"$numberInt":"1"},{"$numberInt":"2"}],"bar":{"hello":"world"},"code":{"$code":"function x() { return 1; }","$scope":{}},"date":{"$date":{"$numberLong":"1721485800000"}}}
159+
160+
Read Extended JSON
161+
------------------
162+
163+
You can read an Extended JSON string into the JavaScript value or object described
164+
by the string by using the ``EJSON.parse()`` method.
165+
166+
The following example shows how you can read an Extended JSON string into a
167+
JavaScript value or object by using the ``parse()`` method:
168+
169+
.. The back ticks on ejsonStr in the below code example causes the orange
170+
.. highlighting in this file, but the page still renders correctly.
171+
172+
.. io-code-block::
173+
174+
.. input::
175+
:language: javascript
176+
177+
import { BSON } from 'mongodb';
178+
const EJSON = BSON.EJSON;
179+
180+
const ejsonStr = `{
181+
"foo": [
182+
{ "$numberInt": "1" },
183+
{ "$numberInt": "2" }
184+
],
185+
"bar": { "hello": "world" },
186+
"code": {
187+
"$code": "function x() { return 1; }",
188+
"$scope": {}
189+
},
190+
"bin": { "$binary": { "base64": "AQIDBA==", "subType": "00" } }
191+
}`;
192+
193+
const doc = EJSON.parse(ejsonStr);
194+
console.log(doc);
195+
196+
.. output::
197+
:language: none
198+
:visible: false
199+
200+
{
201+
foo: [ 1, 2 ],
202+
bar: { hello: 'world' },
203+
code: new Code('function x() { return 1; }', {}),
204+
bin: Binary.createFromBase64('AQIDBA==', 0)
205+
}
206+
207+
.. note::
208+
209+
The driver parses the ``$uuid`` Extended JSON type from a string to a
210+
``BsonBinary`` object of binary subtype 4. For more information about ``$uuid`` field
211+
parsing, see the
212+
:spec:`Special Rules for Parsing $uuid Fields </extended-json/extended-json.md#special-rules-for-parsing-uuid-fields>`
213+
section in the extended JSON specification.
214+
215+
API Documentation
216+
-----------------
217+
218+
To learn more about any of the methods or types discussed in this
219+
guide, see the `EJSON <https://github.com/mongodb/js-bson#ejson>`__ API documentation.

0 commit comments

Comments
 (0)