Search code examples
c#mongodbmongodb-.net-driver

Mongodb How to Update many documents using C# driver


Please be so kind to help.

I got List of documents from xml parsing service and trying update it in DB.

I create fiter builder like .

var filter = Builders<T>.Filter.In("Id", List<T>);

and update builder like.

var update = Builders<T>.Update.Set("T.Property", List<T> )

and using UpdateManyAsync() updating documents in DB, but changings not apply.

How I could update documents in 1 step ?


Solution

  • Hello this is a sample using a .NET core 3.1 console application.

    This is the csproj file:

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>netcoreapp3.1</TargetFramework>
      </PropertyGroup>
    
      <ItemGroup>
        <PackageReference Include="MongoDB.Driver" Version="2.13.1" />
      </ItemGroup>
    
    </Project>
    

    This is the code inside of the Program.cs file:

    using MongoDB.Bson.Serialization.Attributes;
    using MongoDB.Driver;
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    
    namespace MongoUpdateMany
    {
      public static class Program
      {
        public static async Task Main(string[] args)
        {
          const string databaseName = "test";
          const string collectionName = "students";
    
          var client = new MongoClient();
          var database = client.GetDatabase(databaseName);
          var collection = database.GetCollection<Student>(collectionName);
    
          // just to be sure the test data are clean, nothing to do with the update sample
          await database.DropCollectionAsync(collectionName).ConfigureAwait(false);
    
          // create a bunch of students
          var id = 1;
    
          var enrico = new Student()
          {
            Name = "Enrico",
            Id = id++,
            IsActive = false
          };
          var luca = new Student
          {
            Name = "Luca",
            Id = id++,
            IsActive = false
          };
          var giulia = new Student
          {
            Name = "Giulia",
            Id = id++,
            IsActive = true
          };
    
          // fill the collection
          await collection.InsertManyAsync(new List<Student> { enrico, giulia, luca }).ConfigureAwait(false);
    
          // update many
          var ids = new List<int> { enrico.Id, luca.Id };
    
          var filter = Builders<Student>
            .Filter
            .In(x => x.Id, ids);
    
          var update = Builders<Student>
            .Update
            .Set(x => x.IsActive, true);
    
          await collection.UpdateManyAsync(filter, update).ConfigureAwait(false);
    
          // verify updating the docs worked
          await collection
            .Find(student => ids.Contains(student.Id))
            .ForEachAsync(student => Console.WriteLine($"Name: {student.Name} IsActive: {student.IsActive}"))
            .ConfigureAwait(false);
    
          Console.WriteLine();
          Console.WriteLine("Press enter to close...");
          Console.ReadLine();
        }
      }
    
      public class Student
      {
        [BsonId]
        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsActive { get; set; }
      }
    }
    

    Here is some useful links to learn how to use the official C# driver for mongodb: