Skip to content

Commit ceeab63

Browse files
committed
CSHARP-1480: Reference documentation for sync API.
1 parent 971da14 commit ceeab63

File tree

14 files changed

+824
-192
lines changed

14 files changed

+824
-192
lines changed

Docs/reference/content/examples/exporting_json.md

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ title = "Exporting JSON"
1313

1414
The .NET BSON library supports writing JSON documents with the [`JsonWriter`]({{< apiref "T_MongoDB_Bson_IO_JsonWriter" >}}) class.
1515

16-
The program below will export all documents from a collection to a file with one document per line.
16+
The programs below will export all documents from a collection to a file with one document per line. There are two versions of the program, one using the synchronous API and the other using the asynchronous API.
1717

1818
Given the collection's contents:
1919

@@ -25,7 +25,37 @@ Given the collection's contents:
2525
{ "_id" : ObjectId("551330712dfd32ffd580e326"), "x" : 4.0 }
2626
```
2727
28-
And the program:
28+
And the synchronous version of the program:
29+
30+
```csharp
31+
using MongoDB.Bson;
32+
using MongoDB.Bson.IO;
33+
using MongoDB.Bson.Serialization;
34+
using MongoDB.Driver;
35+
36+
// ...
37+
38+
string outputFileName; // initialize to the output file
39+
IMongoCollection<BsonDocument> collection; // initialize to the collection to read from
40+
41+
using (var streamWriter = new StreamWriter(outputFileName))
42+
{
43+
var cursor = collection.Find(new BsonDocument()).ToCursor();
44+
foreach (var document in cursor.ToEnumerable())
45+
{
46+
using (var stringWriter = new StringWriter())
47+
using (var jsonWriter = new JsonWriter(stringWriter))
48+
{
49+
var context = BsonSerializationContext.CreateRoot(jsonWriter);
50+
collection.DocumentSerializer.Serialize(context, document);
51+
var line = stringWriter.ToString();
52+
streamWriter.WriteLine(line);
53+
}
54+
}
55+
}
56+
```
57+
58+
Or the asynchronous version of the program:
2959
3060
```csharp
3161
using MongoDB.Bson;

Docs/reference/content/examples/importing_json.md

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ title = "Importing JSON"
1313

1414
The .NET BSON library supports reading JSON documents with the [`JsonReader`]({{< apiref "T_MongoDB_Bson_IO_JsonReader" >}}) class.
1515

16-
The program below will import all documents from a file with one document per line into the collection.
16+
The programs below will import all documents from a file with one document per line into the collection. There are two versions of the program, one using the synchronous API and the other using the asynchronous API.
1717

1818
Given the input file's contents:
1919

@@ -24,7 +24,35 @@ Given the input file's contents:
2424
{ "_id" : ObjectId("551330712dfd32ffd580e326"), "x" : 4.0 }
2525
```
2626

27-
And the program:
27+
And the synchronous version of the program::
28+
29+
```csharp
30+
using MongoDB.Bson;
31+
using MongoDB.Bson.IO;
32+
using MongoDB.Bson.Serialization;
33+
using MongoDB.Driver;
34+
35+
// ...
36+
37+
string inputFileName; // initialize to the input file
38+
IMongoCollection<BsonDocument> collection; // initialize to the collection to write to.
39+
40+
using (var streamReader = new StreamReader(inputFileName))
41+
{
42+
string line;
43+
while ((line = streamReader.ReadLine()) != null)
44+
{
45+
using (var jsonReader = new JsonReader(line))
46+
{
47+
var context = BsonDeserializationContext.CreateRoot(jsonReader);
48+
var document = collection.DocumentSerializer.Deserialize(context);
49+
collection.InsertOne(document);
50+
}
51+
}
52+
}
53+
```
54+
55+
Or the asynchronous version of the program:
2856

2957
```csharp
3058
using MongoDB.Bson;

Docs/reference/content/examples/tailable_cursor.md

Lines changed: 49 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,58 @@ title = "Using a Tailable Cursor"
1313

1414
MongoDB offers the option to watch a [capped collection]({{< docsref "manual/core/capped-collections/" >}}) for changes using a [tailable cursor]({{< docsref "manual/tutorial/create-tailable-cursor/" >}}).
1515

16-
The code below "tails" the capped collection and outputs documents to the console as they are added. The method also handles the possibility of a dead cursor by tracking the field `insertDate`. New documents are added with increasing values of `insertDate`.
16+
The code below "tails" a capped collection and outputs documents to the console as they are added. The method also handles the possibility of a dead cursor by tracking the field `insertDate`. New documents are added with increasing values of `insertDate`.
1717

1818
{{% note %}}Even though we are using [`BsonDocument`]({{< apiref "T_MongoDB_Bson_BsonDocument" >}}) below, it is possible to use an application defined class by replacing the [`BsonDocument`]({{< apiref "T_MongoDB_Bson_BsonDocument" >}}) references with that of your application defined class.{{% /note %}}
1919

20+
This version of the code uses the synchronous API to tail the capped collection:
21+
22+
```csharp
23+
private static void TailCollection(IMongoCollection<BsonDocument> collection)
24+
{
25+
// Set lastInsertDate to the smallest value possible
26+
BsonValue lastInsertDate = BsonMinKey.Value;
27+
28+
var options = new FindOptions<BsonDocument>
29+
{
30+
// Our cursor is a tailable cursor and informs the server to await
31+
CursorType = CursorType.TailableAwait
32+
};
33+
34+
// Initially, we don't have a filter. An empty BsonDocument matches everything.
35+
BsonDocument filter = new BsonDocument();
36+
37+
// NOTE: This loops forever. It would be prudent to provide some form of
38+
// an escape condition based on your needs; e.g. the user presses a key.
39+
while (true)
40+
{
41+
// Start the cursor and wait for the initial response
42+
using (var cursor = collection.FindSync(filter, options))
43+
{
44+
foreach (var document in cursor.ToEnumerable())
45+
{
46+
// Set the last value we saw
47+
lastInsertDate = document["insertDate"];
48+
49+
// Write the document to the console.
50+
Console.WriteLine(document.ToString());
51+
}
52+
}
53+
54+
// The tailable cursor died so loop through and restart it
55+
// Now, we want documents that are strictly greater than the last value we saw
56+
filter = new BsonDocument("$gt", new BsonDocument("insertDate", lastInsertDate));
57+
}
58+
}
59+
```
60+
61+
This version of the code uses the asynchronous API to tail the capped collection:
62+
2063
```csharp
2164
private static async Task TailCollectionAsync(IMongoCollection<BsonDocument> collection)
2265
{
23-
// Set lastValue to the smallest value possible
24-
BsonValue lastValue = BsonMinKey.Value;
66+
// Set lastInsertDate to the smallest value possible
67+
BsonValue lastInsertDate = BsonMinKey.Value;
2568

2669
var options = new FindOptions<BsonDocument>
2770
{
@@ -43,7 +86,7 @@ private static async Task TailCollectionAsync(IMongoCollection<BsonDocument> col
4386
await cursor.ForEachAsync(document =>
4487
{
4588
// Set the last value we saw
46-
lastValue = document["insertDate"];
89+
lastInsertDate = document["insertDate"];
4790

4891
// Write the document to the console.
4992
await Console.WriteLineAsync(document.ToString());
@@ -52,10 +95,10 @@ private static async Task TailCollectionAsync(IMongoCollection<BsonDocument> col
5295

5396
// The tailable cursor died so loop through and restart it
5497
// Now, we want documents that are strictly greater than the last value we saw
55-
filter = new BsonDocument("$gt", new BsonDocument("insertDate", lastId));
98+
filter = new BsonDocument("$gt", new BsonDocument("insertDate", lastInsertDate));
5699
}
57100
}
58101
```
59102

60103
{{% note %}}If multiple documents might have the exact same insert date, then using the above logic might cause you to miss some documents in the event that the cursor gets restarted. To solve this,
61-
you could track all the documents you've seen by their identifiers for the same `lastValue` and ignore them in the callback. In addition, you would need to change the `$gt` condition to `$gte`{{% /note %}}.
104+
you could track all the documents you've seen by their identifiers for the same `lastInsertDate` and ignore them when restarting the tailable cursor. In addition, you would need to change the `$gt` condition to `$gte`{{% /note %}}.

Docs/reference/content/examples/user_management.md

Lines changed: 50 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ title = "Managing Users"
1111

1212
## How to Manage Users
1313

14-
While MongoDB supports many user management commands, the driver does not have any helpers for them because users are generally managed from the [MongoDB shell]({{< docsref "reference/mongo-shell/" >}}). However, it is still possible to manage users from the driver by using the [`IMongoDatabase.RunCommandAsync`]({{< apiref "M_MongoDB_Driver_IMongoDatabase_RunCommandAsync__1" >}}) method.
14+
While MongoDB supports many user management commands, the driver does not have any helpers for them because users are generally managed from the [MongoDB shell]({{< docsref "reference/mongo-shell/" >}}). However, it is still possible to manage users from the driver by using the [`RunCommand`]({{< apiref "M_MongoDB_Driver_IMongoDatabase_RunCommand__1" >}}) or [`RunCommandAsync`]({{< apiref "M_MongoDB_Driver_IMongoDatabase_RunCommandAsync__1" >}}) methods.
1515

1616

1717
## Listing Users
@@ -24,7 +24,12 @@ var db = client.GetDatabase("products");
2424

2525
// construct the usersInfo command
2626
var command = new BsonDocument("usersInfo", 1);
27-
27+
```
28+
```csharp
29+
// Run the command. If it fails, an exception will be thrown.
30+
var result = db.RunCommand<BsonDocument>(command);
31+
```
32+
```csharp
2833
// Run the command. If it fails, an exception will be thrown.
2934
var result = await db.RunCommandAsync<BsonDocument>(command);
3035
```
@@ -51,22 +56,27 @@ var command = new BsonDocument
5156
{ "pwd", "cleartext password" },
5257
{ "customData", new BsonDocument("employeeId", 12345) },
5358
{ "roles", new BsonArray
54-
{
55-
new BsonDocument
56-
{
57-
{ "role", "clusterAdmin" },
58-
{ "db", "admin" }
59-
},
60-
new BsonDocument
61-
{
62-
{ "role", "readAnyDatabase" },
63-
{ "db", "admin" }
64-
},
65-
"readWrite"
66-
}},
59+
{
60+
new BsonDocument
61+
{
62+
{ "role", "clusterAdmin" },
63+
{ "db", "admin" }
64+
},
65+
new BsonDocument
66+
{
67+
{ "role", "readAnyDatabase" },
68+
{ "db", "admin" }
69+
},
70+
"readWrite"
71+
}},
6772
{ "writeConcern", writeConcern.ToBsonDocument() }
6873
};
69-
74+
```
75+
```csharp
76+
// Run the command. If it fails, an exception will be thrown.
77+
db.RunCommand<BsonDocument>(command);
78+
```
79+
```csharp
7080
// Run the command. If it fails, an exception will be thrown.
7181
await db.RunCommandAsync<BsonDocument>(command);
7282
```
@@ -85,15 +95,20 @@ var command = new BsonDocument
8595
{ "updateUser", "appClient01" },
8696
{ "customData", new BsonDocument("employeeId", "0x3039") },
8797
{ "roles", new BsonArray
88-
{
89-
new BsonDocument
90-
{
91-
{ "role", "read" },
92-
{ "db", "assets" }
93-
},
94-
}}
98+
{
99+
new BsonDocument
100+
{
101+
{ "role", "read" },
102+
{ "db", "assets" }
103+
},
104+
}}
95105
};
96-
106+
```
107+
```csharp
108+
// Run the command. If it fails, an exception will be thrown.
109+
db.RunCommand<BsonDocument>(command);
110+
```
111+
```csharp
97112
// Run the command. If it fails, an exception will be thrown.
98113
await db.RunCommandAsync<BsonDocument>(command);
99114
```
@@ -107,10 +122,17 @@ The following example uses the [`dropUser`]({{< docsref "reference/command/dropU
107122
var db = client.GetDatabase("products");
108123

109124
// Construct the dropUser command.
110-
var command = @"{ dropUser: ""accountAdmin01"",
111-
writeConcern: { w: ""majority"", wtimeout: 5000 }
112-
}";
113-
125+
var command =
126+
@"{
127+
dropUser: ""accountAdmin01"",
128+
writeConcern: { w: ""majority"", wtimeout: 5000 }
129+
}";
130+
```
131+
```csharp
132+
// Run the command. If it fails, an exception will be thrown.
133+
db.RunCommand<BsonDocument>(command);
134+
```
135+
```csharp
114136
// Run the command. If it fails, an exception will be thrown.
115137
await db.RunCommandAsync<BsonDocument>(command);
116138
```

0 commit comments

Comments
 (0)