allowDiskUse在MongoDB c#驱动的聚合框架

本文关键字:框架 MongoDB allowDiskUse | 更新日期: 2023-09-27 18:14:01

我想allowDiskUse:true。然而,我找不到任何例子来解释allowDiskUse启用MongoDB c#驱动程序。

如何在MongoDB c#驱动程序中启用allowDiskUse ?

我的示例代码如下

    var pipeline = new[] { match, project, group, limit, sort, allow };
    List<SMBMostInfluentialUser> result = db
        .GetCollection<SMBTwitterStatus>("TwitterStatus")
        .Aggregate(pipeline).ResultDocuments.Select(x =>
            new User
        {
            Influence = Convert.ToDouble(x["Influence"]),
            User = new SMBUser((BsonDocument)x["User"])
        }).ToList();

allowDiskUse在MongoDB c#驱动的聚合框架

使用Aggregate的另一个重载,它接受AggregateArgs参数,并为您提供对操作的更多控制,包括设置AllowDiskUse:

var pipeline = new BsonDocument[0]; // replace with a real pipeline
var aggregateArgs = new AggregateArgs { AllowDiskUse = true, Pipeline = pipeline };
var aggregateResult = collection.Aggregate(aggregateArgs);
var users = aggregateResult.Select(x =>
    new User
    {
        Influence = x["Influence"].ToDouble(),
        User = new SMBUser(x["user"].AsBsonDocument)
    }).ToList();

注意,这个聚合重载的返回类型是IEnumerable所以你不再需要使用ResultDocuments属性。

要清楚,Select是在客户端执行的。您可以对它进行安排,以便从聚合管道中出来的文档可以直接反序列化到您的一个类的实例中。

对于最新版本的MongoDB c#驱动程序(不确定从哪个版本开始),语法为:

var aggregateOptions = new AggregateOptions{ AllowDiskUse = true};
var aggregateResult = collection.Aggregate(aggregateOptions);