Home > OS >  MongoDB - Query max date in collection
MongoDB - Query max date in collection

Time:09-02

I've got a collection with a registeredtime field and to query the latest insertion:

db.orders.aggregate({ $group: { _id: 1, regt: { $max: "$registeredtime" }}})

Now I want to integrate this into a C# .NET Core MongoDB client but I'm completely stuck on this:

var filter = _collection.Aggregate().Group( _id => ???? )

How to query the max time of a field in C# MongoDB client?

CodePudding user response:

Solution 1: With BsonDocument

BsonDocument groupStage = new BsonDocument
{
    { "_id", 1 },
    { "regt", new BsonDocument("$max", "$registeredtime") }
};

var result = await _collection.Aggregate()
    .Group<BsonDocument>(groupStage)
    .ToListAsync();

Demo

enter image description here


Solution 2: With Expression

Pre-requisites: Create a concrete class for the output result.

class OrderGroup
{
    public int Id { get; set; }

    public DateTime Regt { get; set; }
}
var result = await _collectionAggregate()
    .Group<Order, int, OrderGroup>(x => 1, x => new OrderGroup
    {
        Id = x.Key,
        Regt = x.Max(y => y.Registeredtime)
    })
    .ToListAsync();

Demo

enter image description here


Sample Input Data

[
  {
    "registeredtime": new Date("2021-01-02T01:02:03Z")
  },
  {
    "registeredtime": new Date("2022-09-02T00:00:00Z")
  }
]
  • Related