Exemple #1
0
        public async Task UpdatesDocuments()
        {
            {
                // :code-block-start: mongo-update-one
                var updateResult = await plantsCollection.UpdateOneAsync(
                    new { name = "Petunia" },
                    new BsonDocument("$set", new BsonDocument("sunlight", Sunlight.Partial.ToString()))
                    );

                // :code-block-end:
                Assert.AreEqual(1, updateResult.MatchedCount);
                Assert.AreEqual(1, updateResult.ModifiedCount);
            }
            {
                // :code-block-start: mongo-update-many
                var filter    = new { _partition = "Store 47" };
                var updateDoc = new BsonDocument("$set",
                                                 new BsonDocument("_partition", "Area 51"));

                var updateResult = await plantsCollection.UpdateManyAsync(
                    filter, updateDoc);

                // :code-block-end:
                Assert.AreEqual(1, updateResult.MatchedCount);
                Assert.AreEqual(1, updateResult.ModifiedCount);
            }
            {
                // :code-block-start: mongo-upsert
                var filter = new BsonDocument()
                             .Add("name", "Pothos")
                             .Add("type", PlantType.Perennial)
                             .Add("sunlight", Sunlight.Full);

                var updateResult = await plantsCollection.UpdateOneAsync(
                    filter,
                    new BsonDocument("$set", new BsonDocument("_partition", "Store 42")),
                    upsert : true);

                /* The upsert will create the following object:
                 *
                 * {
                 * "name": "pothos",
                 * "sunlight": "full",
                 * "type": "perennial",
                 * "_partition": "Store 42"
                 * }
                 */
                // :code-block-end:

                var plant = await plantsCollection.FindOneAsync(filter);

                Assert.AreEqual("Store 42", plant.Partition);
                Assert.AreEqual(plant.Id, updateResult.UpsertedId);
            }
        }