Hi,
UpdateOneAsync() and UpdateManyAsync()
are the two functions used to update the data in the mongodb using C# we can
replace the one value with other or else we can increment the value by certain
number.
In
the below example for UpdateOneAsync()
I am updating single document in a MongoDB collection. I am updating MasterID as 11 for the record which
contains MasterID as 10.
In the below example for UpdateManyAsync() I am updating multiple document in a MongoDB
collection. Incrementing value to 10 for the values of MasterID contains
greater than 100
C#: .Net 4.5 and MongoDB 2.0
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Core;
namespace UpdColl
{
class Program
{
static void Main(string[] args)
{
callMain(args).Wait();
Console.ReadLine();
}
static async Task callMain(string[] args)
{
var conString = "mongodb://localhost:27017";
var Client = new MongoClient(conString);
var DB = Client.GetDatabase("test");
var collection = DB.GetCollection<BsonDocument>("MasterIds");
//below
code will update one record of the data
var updoneresult = await collection.UpdateOneAsync(
Builders<BsonDocument>.Filter.Eq("MasterID", 10),
Builders<BsonDocument>.Update.Set("MasterID", 11));
//below
code will update multiple records of the data
var updmanyresult = await collection.UpdateManyAsync(
Builders<BsonDocument>.Filter.Gt("MasterID", 100),
Builders<BsonDocument>.Update.Inc("MasterID", 10));
//below
code retrieves the updated records
await collection.Find(new BsonDocument())
.ForEachAsync(x => Console.WriteLine(x));
}
}
}