Skip to content

Commit 8263eef

Browse files
authored
[DOCSP-24550] BSON (#41)
* wip * first draft * edits and reorg * fixes * fixes * fix file paths * fix * js feedback * feedback * test * test * fix * test * feedback
1 parent 8a80354 commit 8263eef

File tree

5 files changed

+309
-4
lines changed

5 files changed

+309
-4
lines changed

source/fundamentals.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ Fundamentals
1313
/fundamentals/connection
1414
/fundamentals/crud
1515
/fundamentals/builders
16-
/fundamentals/poco
16+
/fundamentals/data-formats
1717
/fundamentals/stable-api
1818
/fundamentals/authentication
1919
/fundamentals/enterprise-authentication

source/fundamentals/data-formats.txt

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
.. _csharp-data-formats:
2+
3+
============
4+
Data Formats
5+
============
6+
7+
.. default-domain:: mongodb
8+
9+
.. toctree::
10+
:caption: Data Formats
11+
12+
/fundamentals/data-formats/bson
13+
/fundamentals/data-formats/poco
Lines changed: 241 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,241 @@
1+
.. _csharp-bson:
2+
3+
==============
4+
Work with BSON
5+
==============
6+
7+
.. default-domain:: mongodb
8+
9+
.. contents:: On this page
10+
:local:
11+
:backlinks: none
12+
:depth: 2
13+
:class: singlecol
14+
15+
Overview
16+
--------
17+
18+
In this guide, you can learn how to create BSON documents, read BSON from a file,
19+
and write BSON to a file using the {+driver-short+}.
20+
21+
BSON Data Format
22+
----------------
23+
24+
**BSON**, or Binary JSON, is the data format that MongoDB uses to organize
25+
and store data. This data format includes all JSON data structure types and
26+
adds support for types including dates, different size integers, ObjectIds, and
27+
binary data. For a complete list of supported types, see the
28+
:manual:`BSON Types </reference/bson-types>` server manual page.
29+
30+
The code samples in this guide use the following BSON document as an example:
31+
32+
.. code-block:: none
33+
34+
{
35+
"address" : {
36+
"street" : "Pizza St",
37+
"zipcode" : "10003"
38+
},
39+
"coord" : [-73.982419, 41.579505]
40+
"cuisine" : "Pizza",
41+
"name" : "Mongo's Pizza"
42+
}
43+
44+
Create a BSON Document
45+
----------------------
46+
47+
To build a BSON document in {+language+}, create an instance of the ``BsonDocument`` class.
48+
The ``BsonDocument`` constructor accepts ``BsonElement`` arguments that map to the fields
49+
and values in the document. Each ``BsonElement`` can be either an instance of the
50+
``BsonElement`` class or a field-value pair inside curly braces ( ``{}`` ).
51+
52+
The following code sample shows how to create a ``BsonDocument`` object to represent the
53+
example BSON document. Each ``BsonElement`` is an instance of the ``BsonElement``
54+
class.
55+
56+
.. literalinclude:: ../../includes/fundamentals/code-examples/Bson.cs
57+
:start-after: start-bson-elements
58+
:end-before: end-bson-elements
59+
:language: csharp
60+
:copyable:
61+
:dedent:
62+
63+
The following code sample creates the same ``BsonDocument``, but each ``BsonElement``
64+
is a field-value pair:
65+
66+
.. literalinclude:: ../../includes/fundamentals/code-examples/Bson.cs
67+
:start-after: start-create
68+
:end-before: newRestaurant.Add
69+
:language: csharp
70+
:copyable:
71+
:dedent:
72+
73+
.. tip::
74+
75+
Each pair of curly braces in a BSON document requires one new ``BsonDocument`` object
76+
in {+language+}.
77+
78+
Change a BSON Document
79+
----------------------
80+
81+
The ``BsonDocument`` class includes methods that let you change the contents of the
82+
BSON document. The following code sample makes three changes to the previous
83+
``BsonDocument`` object:
84+
85+
1. Adds a new field, ``"restaurant_id"``, with the value ``"12345"``
86+
#. Removes the ``"cuisine"`` field
87+
#. Sets the value of the ``"name"`` field to ``"Mongo's Pizza Palace"``
88+
89+
.. literalinclude:: ../../includes/fundamentals/code-examples/Bson.cs
90+
:start-after: start-create
91+
:end-before: end-change
92+
:language: csharp
93+
:copyable:
94+
:dedent:
95+
:emphasize-lines: 15-17
96+
97+
.. note::
98+
99+
For a full list of methods in the ``BsonDocument`` class, see the
100+
:ref:`csharp-bson-api`.
101+
102+
Write BSON to a File
103+
--------------------
104+
105+
You can write BSON to a file using the methods in the ``BsonBinaryWriter`` class. To
106+
write to a file, perform the following steps:
107+
108+
1. Open a file stream for the file containing BSON data.
109+
#. Create a ``BsonBinaryWriter`` using the file stream.
110+
#. For each BSON document and subdocument you want to create, call
111+
``WriteStartDocument()``.
112+
#. Within each BSON document and subdocument, call ``WriteName()`` to set the field
113+
name and the appropriate ``Write*`` method to set its value. Each data type has a
114+
dedicated ``Write*`` method that you should use.
115+
#. To start and end arrays, use ``WriteStartArray()`` and ``WriteEndArray()``.
116+
#. At the end of each document and subdocument, call ``WriteEndDocument()``.
117+
118+
The following code sample shows how to write the sample BSON document to ``myFile.bson``:
119+
120+
.. code-block:: csharp
121+
122+
string outputFileName = "myFile.bson";
123+
124+
using (var stream = File.OpenWrite(outputFileName))
125+
using (var writer = new BsonBinaryWriter(stream))
126+
{
127+
writer.WriteStartDocument();
128+
129+
//address
130+
writer.WriteName("address");
131+
writer.WriteStartDocument();
132+
writer.WriteName("street");
133+
writer.WriteString("Pizza St");
134+
writer.WriteName("zipcode");
135+
writer.WriteString("10003");
136+
writer.WriteEndDocument();
137+
138+
//coord
139+
writer.WriteName("coord");
140+
writer.WriteStartArray();
141+
writer.WriteDouble(-73.982419);
142+
writer.WriteDouble(41.579505);
143+
writer.WriteEndArray();
144+
145+
//cuisine
146+
writer.WriteName("cuisine");
147+
writer.WriteString("Pizza");
148+
149+
//name
150+
writer.WriteName("name");
151+
writer.WriteString("Mongo's Pizza");
152+
153+
writer.WriteEndDocument();
154+
}
155+
156+
The resulting BSON document looks like the following:
157+
158+
.. code-block:: none
159+
160+
{
161+
"address" : {
162+
"street" : "Pizza St",
163+
"zipcode" : "10003"
164+
},
165+
"coord" : [-73.982419, 41.579505]
166+
"cuisine" : "Pizza",
167+
"name" : "Mongo's Pizza"
168+
}
169+
170+
Read BSON from a File
171+
---------------------
172+
173+
To read a BSON document from a file, follow the same steps used for writing a BSON
174+
document to a file, with two differences:
175+
176+
- Use ``BsonBinaryReader`` instead of ``BsonBinaryWriter``.
177+
- Use ``Read*`` methods instead of ``Write*`` methods. These methods return field names
178+
and values from the BSON document.
179+
180+
The following code sample shows how to read the fields and values from the sample
181+
BSON document stored in ``myFile.bson``:
182+
183+
.. code-block:: csharp
184+
185+
string inputFileName = "myFile.bson";
186+
187+
using (var stream = File.OpenRead(inputFileName))
188+
using (var reader = new BsonBinaryReader(stream))
189+
{
190+
reader.ReadStartDocument();
191+
192+
//address
193+
string addressFieldName = reader.ReadName();
194+
reader.ReadStartDocument();
195+
string streetFieldName = reader.ReadName();
196+
string streetValue = reader.ReadString();
197+
string zipFieldName = reader.ReadName();
198+
string zipValue = reader.ReadString();
199+
reader.ReadEndDocument();
200+
201+
//coord
202+
string coordFieldName = reader.ReadName();
203+
reader.ReadStartArray();
204+
double coord1 = reader.ReadDouble();
205+
double coord2 = reader.ReadDouble();
206+
reader.ReadEndArray();
207+
208+
//cuisine
209+
string cuisineFieldName = reader.ReadName();
210+
string cuisineValue = reader.ReadString();
211+
212+
//name
213+
string nameFieldName = reader.ReadName();
214+
string nameValue = reader.ReadString();
215+
216+
reader.ReadEndDocument();
217+
}
218+
219+
.. warning::
220+
221+
If you call ``ReadName()`` twice in a row without reading a value,
222+
the driver will throw an ``InvalidOperationException``.
223+
224+
.. tip::
225+
226+
The ``BsonBinaryReader`` and ``BsonBinaryWriter`` constructors accept any
227+
``System.IO.Stream`` object. This means that you can read or write any location
228+
that can be accessed by a stream.
229+
230+
.. _csharp-bson-api:
231+
232+
API Documentation
233+
-----------------
234+
235+
To learn more about any of the methods or types discussed in this
236+
guide, see the following API documentation:
237+
238+
- `BsonDocument <{+api-root+}/T_MongoDB_Bson_BsonDocument.htm>`__
239+
- `BsonElement <{+api-root+}/T_MongoDB_Bson_BsonElement.htm>`__
240+
- `BsonBinaryReader <{+api-root+}/T_MongoDB_Bson_IO_BsonBinaryReader.htm>`__
241+
- `BsonBinaryWriter <{+api-root+}/T_MongoDB_Bson_IO_BsonBinaryWriter.htm>`__

source/fundamentals/poco.txt renamed to source/fundamentals/data-formats/poco.txt

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ MongoDB collection.
113113
using the Pascal case naming convention, you can use the following
114114
code to use camel case field names in the serialized document:
115115

116-
.. literalinclude:: ../includes/fundamentals/code-examples/poco.cs
116+
.. literalinclude:: ../../includes/fundamentals/code-examples/poco.cs
117117
:start-after: start-conventionpack
118118
:end-before: end-conventionpack
119119
:language: csharp
@@ -230,7 +230,7 @@ serialization-related attributes:
230230
- ``[BsonElement()]``, which specifies custom field names in the camel case naming convention
231231
- ``[BsonRepresentation()]``, which specifies serialization of the ``Price`` field as a BSON ``Double`` type
232232

233-
.. literalinclude:: ../includes/fundamentals/code-examples/poco.cs
233+
.. literalinclude:: ../../includes/fundamentals/code-examples/poco.cs
234234
:start-after: start-model
235235
:end-before: end-model
236236
:language: csharp
@@ -239,7 +239,7 @@ serialization-related attributes:
239239

240240
The following code instantiates a ``Clothing`` object and inserts the document into a collection:
241241

242-
.. literalinclude:: ../includes/fundamentals/code-examples/poco.cs
242+
.. literalinclude:: ../../includes/fundamentals/code-examples/poco.cs
243243
:start-after: start-insert
244244
:end-before: end-insert
245245
:language: csharp
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
using MongoDB.Driver;
2+
3+
namespace Fundamentals;
4+
5+
public class Bson
6+
{
7+
public static void Main(string[] args)
8+
{
9+
//start-create
10+
var newRestaurant = new BsonDocument
11+
{
12+
{ "address", new BsonDocument
13+
{
14+
{ "street", "Pizza St" },
15+
{ "zipcode", "10003" }
16+
}
17+
},
18+
{ "coord", new BsonArray
19+
{-73.982419, 41.579505 }
20+
},
21+
{ "cuisine", "Pizza" },
22+
{ "name", "Mongo's Pizza"}
23+
};
24+
newRestaurant.Add(new BsonElement("restaurant_id", "12345"));
25+
newRestaurant.Remove("cuisine");
26+
newRestaurant.Set("name", "Mongo's Pizza Palace");
27+
//end-change
28+
}
29+
30+
public static void BsonElements()
31+
{
32+
//start-bson-elements
33+
var newRestaurant = new BsonDocument
34+
{
35+
new BsonElement("address", new BsonDocument
36+
{
37+
new BsonElement("street", "Pizza St"),
38+
new BsonElement("zipcode", "10003")
39+
}),
40+
new BsonElement("coord", new BsonArray
41+
{
42+
{-73.982419, 41.579505 }
43+
}),
44+
new BsonElement("cuisine", "Pizza"),
45+
new BsonElement("name", "Mongo's Pizza")
46+
};
47+
//end-bson-elements
48+
}
49+
}
50+
51+

0 commit comments

Comments
 (0)