Skip to content

Commit 3923de2

Browse files
DOCSP-24533 - C# UpdateOne Example (#9)
* initial commit * Apply suggestions from code review Co-authored-by: Jordan Smith <[email protected]> * feedback * Apply suggestions from code review Co-authored-by: Jordan Smith <[email protected]> * feedback Co-authored-by: Jordan Smith <[email protected]>
1 parent ff7972e commit 3923de2

File tree

3 files changed

+278
-0
lines changed

3 files changed

+278
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
using System.Threading.Tasks.Sources;
2+
using MongoDB.Bson;
3+
using MongoDB.Bson.Serialization.Attributes;
4+
using MongoDB.Bson.Serialization.Conventions;
5+
using MongoDB.Driver;
6+
using static System.Console;
7+
8+
namespace CSharpExamples.UsageExamples;
9+
10+
public class UpdateOne
11+
{
12+
private static IMongoCollection<Restaurant> _restaurantsCollection;
13+
private static string _mongoConnectionString = "<Your MongoDB URI>";
14+
15+
public static void Main(string[] args)
16+
{
17+
Setup();
18+
19+
// Extra space for console readability
20+
WriteLine();
21+
22+
// Update one document synchronously
23+
var syncResult = UpdateOneRestaurant();
24+
WriteLine($"Updated documents: {syncResult.ModifiedCount}");
25+
ResetSampleData();
26+
}
27+
28+
private static UpdateResult UpdateOneRestaurant()
29+
{
30+
// start-update-one
31+
const string oldValue = "Bagels N Buns";
32+
const string newValue = "2 Bagels 2 Buns";
33+
34+
var filter = Builders<Restaurant>.Filter
35+
.Eq("name", oldValue);
36+
37+
var update = Builders<Restaurant>.Update
38+
.Set(restaurant => restaurant.Name, newValue);
39+
40+
var result = _restaurantsCollection.UpdateOne(filter, update);
41+
return result;
42+
// end-update-one
43+
}
44+
45+
private static void Setup()
46+
{
47+
// This allows automapping of the camelCase database fields to our models.
48+
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
49+
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
50+
51+
// Establish the connection to MongoDB and get the restaurants database
52+
var mongoClient = new MongoClient(_mongoConnectionString);
53+
var restaurantsDatabase = mongoClient.GetDatabase("sample_restaurants");
54+
_restaurantsCollection = restaurantsDatabase.GetCollection<Restaurant>("restaurants");
55+
}
56+
57+
private static void ResetSampleData()
58+
{
59+
var filter = Builders<Restaurant>.Filter
60+
.Eq("name", "2 Bagels 2 Buns");
61+
62+
var update = Builders<Restaurant>.Update
63+
.Set(restaurant => restaurant.Name, "Bagels N Buns");
64+
65+
_restaurantsCollection.UpdateOne(filter, update);
66+
}
67+
}
68+
69+
// start-model
70+
public class Restaurant
71+
{
72+
public ObjectId Id { get; set; }
73+
74+
[BsonElement("name")]
75+
public string Name { get; set; }
76+
77+
[BsonElement("restaurant_id")]
78+
public string RestaurantId { get; set; }
79+
80+
public string Cuisine { get; set; }
81+
82+
public object Address { get; set; }
83+
84+
public string Borough { get; set; }
85+
86+
public List<object> Grades { get; set; }
87+
}
88+
// end-model
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
using System.Threading.Tasks.Sources;
2+
using MongoDB.Bson;
3+
using MongoDB.Bson.Serialization.Attributes;
4+
using MongoDB.Bson.Serialization.Conventions;
5+
using MongoDB.Driver;
6+
using static System.Console;
7+
8+
namespace CSharpExamples.UsageExamples;
9+
10+
public class UpdateOneAsync
11+
{
12+
private static IMongoCollection<Restaurant> _restaurantsCollection;
13+
private static string _mongoConnectionString = "<Your MongoDB URI>";
14+
15+
public static void Main(string[] args)
16+
{
17+
Setup();
18+
19+
// Extra space for console readability
20+
WriteLine();
21+
22+
//Update one document asynchronously
23+
var asyncResult = UpdateOneRestaurantAsync();
24+
WriteLine($"Updated documents: {asyncResult.Result.ModifiedCount}");
25+
ResetSampleData();
26+
}
27+
28+
private static async Task<UpdateResult> UpdateOneRestaurantAsync()
29+
{
30+
// start-update-one-async
31+
const string oldValue = "Bagels N Buns";
32+
const string newValue = "2 Bagels 2 Buns";
33+
34+
var filter = Builders<Restaurant>.Filter
35+
.Eq("name", oldValue);
36+
37+
var update = Builders<Restaurant>.Update
38+
.Set(restaurant => restaurant.Name, newValue);
39+
40+
return await _restaurantsCollection.UpdateOneAsync(filter, update);
41+
// end-update-one-async
42+
43+
}
44+
45+
private static void Setup()
46+
{
47+
// This allows automapping of the camelCase database fields to our models.
48+
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
49+
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
50+
51+
// Establish the connection to MongoDB and get the restaurants database
52+
var mongoClient = new MongoClient(_mongoConnectionString);
53+
var restaurantsDatabase = mongoClient.GetDatabase("sample_restaurants");
54+
_restaurantsCollection = restaurantsDatabase.GetCollection<Restaurant>("restaurants");
55+
}
56+
57+
private static void ResetSampleData()
58+
{
59+
var filter = Builders<Restaurant>.Filter
60+
.Eq("name", "2 Bagels 2 Buns");
61+
62+
var update = Builders<Restaurant>.Update
63+
.Set(restaurant => restaurant.Name, "Bagels N Buns");
64+
65+
_restaurantsCollection.UpdateOne(filter, update);
66+
}
67+
}
68+
69+
// start-model
70+
public class Restaurant
71+
{
72+
public ObjectId Id { get; set; }
73+
74+
[BsonElement("name")]
75+
public string Name { get; set; }
76+
77+
[BsonElement("restaurant_id")]
78+
public string RestaurantId { get; set; }
79+
80+
public string Cuisine { get; set; }
81+
82+
public object Address { get; set; }
83+
84+
public string Borough { get; set; }
85+
86+
public List<object> Grades { get; set; }
87+
}
88+
// end-model

source/usage-examples/updateOne.txt

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
.. _csharp-update-one:
2+
3+
=================
4+
Update a Document
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+
You can update a single document using the `UpdateOne() <{+api-root+}/M_MongoDB_Driver_IMongoCollection_1_UpdateOne.htm>`__ method on
16+
a ``MongoCollection`` object. This method requires a **query filter**, which specifies which document to update, and an **update** statement, which specifies the changes the driver should make to the matching document.
17+
18+
.. note::
19+
20+
The ``UpdateOne()`` method updates only the first document that matches the filter. To update more than one document, use the ``UpdateMany()`` method.
21+
TODO: Link to UpdateMany usage example page.
22+
23+
.. tip::
24+
25+
You can pass an instance of `UpdateOptions <{+api-root+}/T_MongoDB_Driver_UpdateOptions.htm>`__ to the ``UpdateOne()`` method in
26+
order to customize its behavior.
27+
28+
Examples
29+
--------
30+
31+
These examples use the following ``Restaurant`` class as a model:
32+
33+
.. literalinclude:: ../includes/code-examples/UpdateOne.cs
34+
:start-after: start-model
35+
:end-before: end-model
36+
:language: csharp
37+
:copyable:
38+
:dedent:
39+
40+
.. tabs::
41+
42+
.. tab:: Async
43+
:tabid: update-async
44+
45+
Update a Document Asynchronously
46+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
47+
48+
The following example uses builders to asynchronously update the ``name`` of the first document named "Bagels N Buns" in the ``restaurants`` collection to "2 Bagels 2 Buns":
49+
50+
.. literalinclude:: ../includes/code-examples/UpdateOneAsync.cs
51+
:start-after: start-update-one-async
52+
:end-before: end-update-one-async
53+
:language: csharp
54+
:copyable:
55+
:dedent:
56+
57+
.. tab:: Synchronous
58+
:tabid: update-sync
59+
60+
Update a Document Synchronously
61+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
62+
63+
The following example uses builders to synchronously update the ``name`` of the first document named "Bagels N Buns" in the ``restaurants`` collection to "2 Bagels 2 Buns":
64+
65+
.. literalinclude:: ../includes/code-examples/UpdateOne.cs
66+
:start-after: start-update-one
67+
:end-before: end-update-one
68+
:language: csharp
69+
:copyable:
70+
:dedent:
71+
72+
Expected Result
73+
~~~~~~~~~~~~~~~
74+
75+
After running the :ref:`full example <find-runnable-example>`, each call to ``UpdateOne()`` writes the following to the console:
76+
77+
.. code-block:: none
78+
79+
Updated documents: 1
80+
81+
.. tip::
82+
83+
``UpdateOne()`` returns an `UpdateResult <{+api-root+}/T_MongoDB_Driver_UpdateResult.htm>`__ object.
84+
85+
More Information
86+
----------------
87+
88+
.. _find-runnable-example:
89+
90+
For fully runnable examples of the ``UpdateOne()`` operations on this page, see the
91+
`UpdateOne Example <{+example+}/UpdateOne.cs>`__ and `UpdateOneAsync Example <{+example+}/UpdateOneAsync.cs>`__
92+
93+
.. TODO: Add links to references once pages are done
94+
95+
To learn more about builders, see <builders page>.
96+
97+
API Documentation
98+
-----------------
99+
100+
* `UpdateOne() <{+api-root+}/M_MongoDB_Driver_IMongoCollection_1_UpdateOne.htm>`__
101+
* `UpdateOptions <{+api-root+}/T_MongoDB_Driver_UpdateOptions.htm>`__
102+
* `UpdateResult <{+api-root+}/T_MongoDB_Driver_UpdateResult.htm>`__

0 commit comments

Comments
 (0)