Search code examples
c#mongodbmaxmin

How to get Min and Max values from Mongo DB in 1 query? C#


I can get the min and max in 2 Queries, but is it possible with C# to do it with 1?

var max = (await collection.Sort(descendingDateTime).Limit(1).FirstOrDefaultAsync())
                        .GetValue(timeField).ToUniversalTime();

var min = (await collection.Sort(ascendingDateTime).Limit(1).FirstOrDefaultAsync())
                        .GetValue(timeField).ToUniversalTime();

Solution

  • you could do it with a group aggregation like below but it will not be efficient for very large collections as the grouping will cause a collection scan and use up memory (where it might hit the 100mb limit for grouping). it would be better to do it with 2 find queries since it can use an index. as an improvement, you could run both queries somewhat simulaneously by using await Task.WhenAll(minTask, maxTask)

    db.collection.aggregate(
    [
    
        {
            $group: {
                _id: null,
                Min: { $min: "$TimeField" },
                Max: { $max: "$TimeField" }
    
            }
        },
        {
            $project: {
                _id: 0
            }
        }
    
    ])
    

    also there's no way afaik to translate the above aggregation pipeline to a strongly-typed c# query as the driver doesn't support grouping by a null id.