Mongodb C# - How to get max date - ( Aggregate )

The documents look like this:

{
  ContractNumer: 10,
  SomeField: "ABC",
  ValueContract: 17.7,
  DataProcessing: '2021-01-19 10:23:20:10',
  Status: 1
}

With C# mongodb driver, how do you write something like this?

Select ContractNumer, SomeField, ValueContract, DataProcessing, Status
FROM TAB T1
INNER JOIN 
(SELCT ContractNumer, MAX(DataProcessing) AS MAX_DATE FROM TAB) SUB_T
ON T1.ContractNumer = SUB_T.ContractNumer 
AND T1.DataProcessing = SUB_T.MAX_DATE 
WHERE ....

So that for each combination (group) of ContractNumber we'll get max of DataProcessing

1 answer

  • answered 2021-01-19 11:00 Gibbs

    This will help you

    db.collection.aggregate([
      {
        $group: {
          "_id": "$ContractNumer", //Group
          "max": {
            "$max": "$DataProcessing" //Find max
          }
        }
      }
    ])
    

    Try it out in c# and post the question with your attempts.