0

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

The exception was thrown on the line following.

result = trackCollection.Aggregate()
    .Match(x => DateTime.Parse(x.ProcessedDate) > DateTime.Now.AddMinutes(-3))
    .ToList();
public class Track
{
    [BsonElement("processeddate")]
    public string ProcessedDate { get; set; }
    ...
}

processeddate is a string in MongoDB collection.

How to compare string and date time in Match expression using EFCore MongoDB driver?

Although it works I don't prefer this way due to performance issues:

result = trackCollection.Aggregate()
    .ToList()
    .Where(x => DateTime.Parse(x.ProcessedDate) > DateTime.Now.AddMinutes(-3))
    .ToList();
Tolga Cakir
  • 725
  • 1
  • 7
  • 13

1 Answers1

0

Options:

  1. You can define your POCO property like:

    [BsonDateTimeOptions(Representation = BsonType.String)]
    public DateTime Date { get; set; }
    

which will allow you to work with DateTime on the c# side and a simple string in mongo document. All magic will happen in serialization steps.

  1. I don't think that it's possible via any other typed way, however it's supported on MQL level, see: Possible to compare date strings in mongodb?. Also in raw MQL you can use $toDate

So you should either create your match stage as a raw MQL string with fields definitions as in the mongo document like:

  ... 
  .Match("raw MQL $match query")
  ...

or you can transform a string representation of date into mongo date in the stage before $match via $project or $addFields. Then in $match stage you will have already converted date value

dododo
  • 3,872
  • 1
  • 14
  • 37
  • First option: FormatException was thrown with this message: An error occurred while deserializing the Date property of class ...Track: String '2021-10-06 11:53:29' was not recognized as a valid DateTime.' – Tolga Cakir Oct 06 '21 at 08:57
  • Second option: I can't implement that because of my mongodb version (v3.2.9) does not support `$toDate`, `$dateFromString` operators. – Tolga Cakir Oct 06 '21 at 09:01
  • First option: then you may need to implement a custom serializer (for example via `BsonSerializerAttribute`) similar to how it's done here https://stackoverflow.com/questions/67128708/setting-mongodb-to-change-a-property-to-uppercase/67129599#67129599 – dododo Oct 06 '21 at 16:19
  • Second option: you still can use `new Date(processedDate)`, I'm not sure off the top of my head how it can be done on so old server, but you may look at $find-projection or $where https://docs.mongodb.com/manual/reference/operator/query/where/ – dododo Oct 06 '21 at 16:26