MongoDB:如何查找多个文档并同时更新?

时间:2016-09-09 22:39:15

标签: mongodb mongodb-.net-driver

我有mongo DB,我使用C#.Net与mongo db进行交互。 C#API提供了查找单个文档并同时更新文档的方法。例如FindOneAndUpdateAsync
但是,我无法找到任何方法来查找多个文档并同时异步更新它们。

以下代码异步查找和处理每个文档。我如何同时更新该文档?

    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;
    }

1 个答案:

答案 0 :(得分:0)

mongo .Net api中不存在here

只需使用查找 UpdateManyAsync 的组合。