Adarsh s
Adarsh s

Reputation: 308

MongoDB .NET Driver - Convert string to DateTime and for Filter Builder

var builder = Builders<ModelClass>.Filter;
var filter = builder.Where(x => x.Active);

if (fromDate.HasValue)
{
    var date = fromDate.Value;
    var subfilter = builder.Where(x => DateTime.Parse(x.EnrollmentDate) >= date);
    filter &= subfilter;
}

Enrollment Date is saved as a string:

public string EnrollmentDate { get; set; }

, I need to filter docs within a set of date range, but how do I compare this? I need to filter like this.

I get

System.InvalidOperationException: Parse({document}{EnrollmentDate}) is not supported.

Error in subfilter line.

Upvotes: 2

Views: 2570

Answers (3)

Guy_g23
Guy_g23

Reputation: 385

I had the same error with DateTime parsing in MongoDB so I'd suggest you to refactor EnrollmentDate in your model to DateTime. MongoDB knows how to persist DateTime and how to Filter and Sort by it without having to change your subfilters.

Upvotes: 0

Yong Shun
Yong Shun

Reputation: 51125

I think you need to achieve with MongoDB query as below:

{
  "$expr": {
    "$gte": [
      { "$toDate": "$EnrollmentDate" },
      date
    ]
  }
}

While I think it is not achievable with MongoDB .Net Driver LINQ syntax, you convert the query as BsonDocument:

var subfilter = new BsonDocument("$expr",
    new BsonDocument("$gte", 
        new BsonArray {
            new BsonDocument("$toDate", "$EnrollmentDate"),
            date
        }
    )
);

filter &= subfilter;

Upvotes: 2

Radovancev
Radovancev

Reputation: 306

You have problem here when you want to do DateTime.Parse()

Can you post format of your string EnrollmentDate? And your variable date , is it only Date or DateTime?

This one maybe can help you here

Also, try to use

var subfilter = builder.Gte(x=>x.Y, Z) 

Upvotes: 1

Related Questions