2

I have mongo DB and I am using C#.Net to interact with mongo db. C# API has methods for finding a single document and updating it at the same time. For example FindOneAndUpdateAsync.
However I couldn't find any method to find multiple documents and update them at the same time asynchronously.

The code below finding and processing each document asynchronously. How do I also update that document at the same time?

    public async Task<IList<IDictionary<string, string>>> DoWork()
    {
        var collection = _mongoDatabase.GetCollection<BsonDocument>("units");
        var filterBuilder = Builders<BsonDocument>.Filter;
        var filter = filterBuilder.Ne<string>("status", "INIT") &
            (filterBuilder.Exists("isDone", false) |
            filterBuilder.Eq<bool>("isDone", false));

        // I want to pass this update filter to update the document. But not sure how
        var update = Builders<BsonDocument>.Update
           .CurrentDate("startTime");

        var sort = Builders<BsonDocument>.Sort.Ascending("startTime");

        var projection = Builders<BsonDocument>.Projection
            .Include("_id")                
            .Include("fileName");  // for bravity i have removed other projection elements

        var output = new List<IDictionary<string, string>>();

        // How do i pass update filter and update the document at the same time?? 
        await collection
            .Find(filter)
            .Sort(sort)
            .Project(projection)                
            .ForEachAsync((unit) =>
            {
                var dictionary = new Dictionary<string, string>();
                Recurse(unit, dictionary);
                output.Add(dictionary);
            });

        return output.Count > 0 ? output : null;
    }
LP13
  • 30,567
  • 53
  • 217
  • 400

1 Answers1

0

That doesn't exist in the mongo .Net api see here.

Just use a combination of Find and UpdateManyAsync.

Community
  • 1
  • 1
sauce
  • 592
  • 4
  • 9
  • 25
  • I was looking for how to do it? Do I write it in one command or 2 separate calls? – LP13 Sep 10 '16 at 15:28
  • Two separate calls: flow should be use find to retrieve your documents, manipulate the attributes on the documents as necessary, use UpdateMany to save them all. Take a look at the mongo api docs for exact examples of how to use those calls. – sauce Sep 10 '16 at 16:10