Skip to content

Commit 098048b

Browse files
authored
DOCSP-24535 - ReplaceOne page (#20)
* testing code files * initial commit
1 parent dc72310 commit 098048b

File tree

5 files changed

+261
-0
lines changed

5 files changed

+261
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
using MongoDB.Bson;
2+
using MongoDB.Bson.Serialization.Conventions;
3+
using MongoDB.Driver;
4+
using static System.Console;
5+
6+
namespace CSharpExamples.UsageExamples.ReplaceOne;
7+
8+
public class ReplaceOne
9+
{
10+
private static IMongoCollection<Restaurant> _restaurantsCollection;
11+
private const string MongoConnectionString = "<Your MongoDB URI>";
12+
13+
public static void Main(string[] args)
14+
{
15+
Setup();
16+
17+
// Create filter
18+
var filter = Builders<Restaurant>.Filter.Eq("cuisine", "Pizza");
19+
20+
// Find first pizza restaurant
21+
var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First();
22+
WriteLine($"First pizza restaurant before replacement: {oldPizzaRestaurant.Name}");
23+
24+
// Replace one document synchronously
25+
var syncResult = ReplaceOneRestaurant();
26+
WriteLine($"Restaurants modified by replacement: {syncResult.ModifiedCount}");
27+
28+
var firstPizzaRestaurant = _restaurantsCollection.Find(filter).First();
29+
WriteLine($"First pizza restaurant after replacement: {firstPizzaRestaurant.Name}");
30+
31+
Write("Resetting sample data...");
32+
_restaurantsCollection.ReplaceOneAsync(filter, oldPizzaRestaurant);
33+
WriteLine("done.");
34+
}
35+
36+
private static ReplaceOneResult ReplaceOneRestaurant()
37+
{
38+
// start-replace-one
39+
var filter = Builders<Restaurant>.Filter.Eq("cuisine", "Pizza");
40+
41+
// Find ID of first pizza restaurant
42+
var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First();
43+
var oldId = oldPizzaRestaurant.Id;
44+
45+
Restaurant newPizzaRestaurant = new()
46+
{
47+
Id = oldId,
48+
Name = "Mongo's Pizza",
49+
Cuisine = "Pizza",
50+
Address = new BsonDocument
51+
{
52+
{"street", "Pizza St"},
53+
{"zipcode", "10003"},
54+
},
55+
Borough = "Manhattan",
56+
};
57+
58+
return _restaurantsCollection.ReplaceOne(filter, newPizzaRestaurant);
59+
// end-replace-one
60+
}
61+
62+
private static void Setup()
63+
{
64+
// This allows automapping of the camelCase database fields to our models.
65+
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
66+
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
67+
68+
// Establish the connection to MongoDB and get the restaurants database
69+
var mongoClient = new MongoClient(MongoConnectionString);
70+
var restaurantsDatabase = mongoClient.GetDatabase("sample_restaurants");
71+
_restaurantsCollection = restaurantsDatabase.GetCollection<Restaurant>("restaurants");
72+
}
73+
}
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
using MongoDB.Bson;
2+
using MongoDB.Bson.Serialization.Conventions;
3+
using MongoDB.Driver;
4+
using static System.Console;
5+
6+
namespace CSharpExamples.UsageExamples.ReplaceOne;
7+
8+
public class ReplaceOneAsync
9+
{
10+
private static IMongoCollection<Restaurant> _restaurantsCollection;
11+
private const string MongoConnectionString = "<Your MongoDB URI>";
12+
13+
public static void Main(string[] args)
14+
{
15+
Setup();
16+
17+
// Create filter
18+
var filter = Builders<Restaurant>.Filter.Eq("cuisine", "Pizza");
19+
20+
// Find first pizza restaurant
21+
var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First();
22+
WriteLine($"First pizza restaurant before replacement: {oldPizzaRestaurant.Name}");
23+
24+
// Replace one document synchronously
25+
var asyncResult = ReplaceOneRestaurant();
26+
WriteLine($"Restaurants modified by replacement: {asyncResult.Result.ModifiedCount}");
27+
28+
var firstPizzaRestaurant = _restaurantsCollection.Find(filter).First();
29+
WriteLine($"First pizza restaurant after replacement: {firstPizzaRestaurant.Name}");
30+
31+
Write("Resetting sample data...");
32+
_restaurantsCollection.ReplaceOneAsync(filter, oldPizzaRestaurant);
33+
WriteLine("done.");
34+
}
35+
36+
private static async Task<ReplaceOneResult> ReplaceOneRestaurant()
37+
{
38+
// start-replace-one-async
39+
var filter = Builders<Restaurant>.Filter.Eq("cuisine", "Pizza");
40+
41+
// Find ID of first pizza restaurant
42+
var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First();
43+
var oldId = oldPizzaRestaurant.Id;
44+
45+
Restaurant newPizzaRestaurant = new()
46+
{
47+
Id = oldId,
48+
Name = "Mongo's Pizza",
49+
Cuisine = "Pizza",
50+
Address = new BsonDocument
51+
{
52+
{"street", "Pizza St"},
53+
{"zipcode", "10003"},
54+
},
55+
Borough = "Manhattan",
56+
};
57+
58+
return await _restaurantsCollection.ReplaceOneAsync(filter, newPizzaRestaurant);
59+
// end-replace-one-async
60+
}
61+
62+
private static void Setup()
63+
{
64+
// This allows automapping of the camelCase database fields to our models.
65+
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
66+
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
67+
68+
// Establish the connection to MongoDB and get the restaurants database
69+
var mongoClient = new MongoClient(MongoConnectionString);
70+
var restaurantsDatabase = mongoClient.GetDatabase("sample_restaurants");
71+
_restaurantsCollection = restaurantsDatabase.GetCollection<Restaurant>("restaurants");
72+
}
73+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
using MongoDB.Bson;
2+
using MongoDB.Bson.Serialization.Attributes;
3+
4+
namespace CSharpExamples.UsageExamples.ReplaceOne;
5+
6+
//start-model
7+
public class Restaurant
8+
{
9+
public ObjectId Id { get; set; }
10+
11+
public string Name { get; set; }
12+
13+
[BsonElement("restaurant_id")]
14+
public string RestaurantId { get; set; }
15+
16+
public string Cuisine { get; set; }
17+
18+
public object Address { get; set; }
19+
20+
public string Borough { get; set; }
21+
22+
public List<object> Grades { get; set; }
23+
}
24+
//end-model

source/usage-examples.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,6 @@ TODO: Write usage examples page
1414
/usage-examples/insertMany
1515
/usage-examples/updateOne
1616
/usage-examples/updateMany
17+
/usage-examples/replaceOne
1718
/usage-examples/deleteOne
1819
/usage-examples/deleteMany

source/usage-examples/replaceOne.txt

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
.. _csharp-replace-one:
2+
3+
====================
4+
Replace One 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 replace one document with another by using the ``ReplaceOne()`` synchronous method
16+
or the ``ReplaceOneAsync()`` asynchronous method on a collection object.
17+
18+
Example
19+
-------
20+
21+
This example uses the following ``Restaurant`` class as a model:
22+
23+
.. literalinclude:: ../includes/code-examples/replace-one/Restaurant.cs
24+
:start-after: start-model
25+
:end-before: end-model
26+
:language: csharp
27+
:copyable:
28+
:dedent:
29+
30+
The following code replaces the first document in the ``restaurants`` collection that has a
31+
value of "Pizza" in the ``cuisine`` field. After the replacement, this document will
32+
have a ``name`` field with a value of "Mongo's Pizza" and new values for the
33+
``address`` and ``borough`` fields.
34+
35+
Select the :guilabel:`Asynchronous` or :guilabel:`Synchronous` tab to see the
36+
corresponding code.
37+
38+
.. tabs::
39+
40+
.. tab:: Asynchronous
41+
:tabid: replace-one-async
42+
43+
.. literalinclude:: ../includes/code-examples/replace-one/ReplaceOneAsync.cs
44+
:start-after: start-replace-one-async
45+
:end-before: end-replace-one-async
46+
:language: csharp
47+
:copyable:
48+
:dedent:
49+
50+
For a fully runnable example of the ``ReplaceOneAsync()`` operation, see the
51+
`ReplaceOneAsync code sample <{+example+}/replace-one/ReplaceOneAsync.cs>`__.
52+
53+
.. tab:: Synchronous
54+
:tabid: replace-one-sync
55+
56+
.. literalinclude:: ../includes/code-examples/replace-one/ReplaceOne.cs
57+
:start-after: start-replace-one
58+
:end-before: end-replace-one
59+
:language: csharp
60+
:copyable:
61+
:dedent:
62+
63+
For a fully runnable example of the ``ReplaceOne()`` operation, see the
64+
`ReplaceOne code sample <{+example+}/replace-one/ReplaceOne.cs>`__.
65+
66+
Expected Result
67+
~~~~~~~~~~~~~~~
68+
69+
Running either of the preceding full examples prints the following results:
70+
71+
.. code-block:: none
72+
73+
First pizza restaurant before replacement: J&V Famous Pizza
74+
Restaurants modified by replacement: 1
75+
First pizza restaurant after replacement: Mongo's Pizza
76+
Resetting sample data...done.
77+
78+
79+
More Information
80+
----------------
81+
82+
.. TODO: Add links to Fundamentals once pages are done
83+
84+
API Documentation
85+
-----------------
86+
87+
* `ReplaceOne() <{+api-root+}/M_MongoDB_Driver_IMongoCollection_1_ReplaceOne.htm>`__
88+
* `ReplaceOneAsync() <{+api-root+}/M_MongoDB_Driver_IMongoCollection_1_ReplaceOneAsync.htm>`__
89+
* `ReplaceOptions <{+api-root+}/T_MongoDB_Driver_ReplaceOptions.htm>`__
90+
* `ReplaceOneResult <{+api-root+}/T_MongoDB_Driver_ReplaceOneResult.htm>`__

0 commit comments

Comments
 (0)