Search code examples
c#mongodbmongodb-.net-driver

MongoDriver c# Filter by month Name from a Date Field


Requirement : Need to filter the mongo documents by month (Data is stored in mongo as date time)

Code used : var expenseMonthFilter = Builders<MyDocument>.Filter.Eq(i => i.ExpenseDate.Month, 12);

Exception Getting :Unable to determine the serialization information for i => i.ExpenseDate.Month.

Mongo Data Image


Solution

  • When selecting all the document of a month, the condition needs to retrieve all documents that have a ExpenseDate that is greather than or equal to the start date of the month and less than the start date of the following month, like so:

    var startOfMonth = new DateTime(selectedYear, selectedMonth, 1, 0, 0, 0, DateTimeKind.Utc);
    var startOfNextMonth = startOfMonth.AddMonths(1);
    var bldr = Builders<MyDocument>.Filter;
    var expenseMonthFilter = bldr.And(
        bldr.Gte(x => x.ExpenseDate, startOfMonth), 
        bldr.Lt(x => x.ExpenseDate, startOfNextMonth));
    

    Please not that in the sample above, selectedYear stands for the year, selectedMonth for the month that the data should be retrieved for.