You can use the UpdateOneAsync method, UpdateManyAsync method, and ReplaceOneAsync method to update documents of a collection. The methods accept the following parameters:
- a filter document to match the documents to update,
- an update document to specify the modification to perform, and
- an options parameter (optional).
You cannot update the _id field.
Follow the Install and Connect to MongoDB step to connect to a running MongoDB instance.
The following operation updates the first document with Name equal to “Himen”, to update the Email, Address1, City, ZipCode and Country field and the lastModified field. To specify a $set operation to update the Email, Address1, City, ZipCode and Country field, use the Set method of the UpdateDefinitionBuilder. To specify a $currentDate operation to update the lastModified field with the current date, use the CurrentDate method of the UpdateDefinitionBuilder.
The $set operator replaces the value of a field with the specified value.
The $currentDate operator sets the value of a field to the current date, either as a Dateor a timestamp. The default type is Date.
using System;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
namespace MongoDB
{
class Program
{
static void Main(string[] args)
{
UpdateDoc(args).Wait();
Console.WriteLine("Press Enter");
Console.ReadLine();
}
static async Task UpdateDoc(string[] args)
{
var _connectionString = "mongodb://localhost:27017";
var _client = new MongoClient(_connectionString);
var _database = _client.GetDatabase("blog");
var _collection = _database.GetCollection("users");
var _filter = Builders.Filter.Eq("Name", "Test");
var _update = Builders.Update
.Set("Email", "email2test@zzzz.com")
.Set("Address1", "other street")
.Set("City", "XYZ")
.Set("ZipCode", "390011")
.Set("Country", "other country")
.CurrentDate("lastModified");
var _result = await _collection.UpdateOneAsync(_filter, _update);
}
}
}