Dreamcatcher
Dreamcatcher

Reputation: 828

allowDiskUse in Aggregation Framework with MongoDB C# Driver

I would like to allowDiskUse:true. However I could not found any example which explain allowDiskUse enabling for MongoDB C# driver.

How can I enable allowDiskUse in MongoDB C# driver?

My sample code like that

    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();

Upvotes: 6

Views: 8240

Answers (2)

July.Tech
July.Tech

Reputation: 1376

For more recent versions of MongoDB C# driver (not sure starting with what version), the syntax is:

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

Upvotes: 7

Robert Stam
Robert Stam

Reputation: 12187

Use the other overload of Aggregate that takes an AggregateArgs parameter and gives you more control over the operation, including setting 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();

Note that the return type of this overload of Aggregate is IEnumerable<BsonDocument> so you no longer have to use the ResultDocuments property.

Just to be clear, the Select is being executed client side. You might be able to arrange it so that the documents coming out of your aggregation pipeline can be directly deserialized into instances of one of your classes.

Upvotes: 7

Related Questions