1

I have a MongoDB collection of objects like this.

{
    "_id" : "56fd034268f44e1eccb8a775",
    "Period" : {
            "StartDateTime" : ISODate("2016-04-02T06:00:00Z"),
            "EndDateTime" : ISODate("2016-04-02T08:00:00Z")
    },
    ... //other attributes here
}
{
    "_id" : "56fd034968f44e1eccb8a776",
    "Period" : {
            "StartDateTime" : ISODate("2016-04-04T06:00:00Z"),
            "EndDateTime" : ISODate("2016-04-04T07:30:00Z")
    },
    ... //other attributes here
}

I want to create a strongly-typed aggregation query to compute the total elapsed time, for all time slices.

I wrote this statement.

var aggregate = coll.Aggregate()
            .Project(r => new { duration = r.Period.EndDateTime - r.Period.StartDateTime })
            .Group(k => 0, g => g.Sum(x => x.duration));

But I receive the following error.

Cannot implicitly convert type 'System.TimeSpan' to 'int'

Is there a solution? Have I to switch to BsonDocument approach?

Marcello
  • 879
  • 6
  • 20
  • Use the BSON document approach. MongoDB driver translation of LINQ expressions is not at "exact" science. The BSON expressions are far more directly expressive. Also a waste of time to `$project` here when you can just calculate the "duration" directly in the `$sum` accumulator in `$group`. And with BSON expressions that is **easy**. – Blakes Seven Mar 31 '16 at 11:22
  • Note also your big fail here is "strongly typed". The subtraction of `Date` objects in BSON yields an "integer" representing the milliseconds difference between the two objects. So it's not the same "type" as the input. – Blakes Seven Mar 31 '16 at 11:24
  • Thanks for the hint on useless projection stage. IMO strongly-typed queries are **awesome**. They are compile-time checked and refactoring friendly. BsonDocument approach resembles very much hardcoded SQL-queries and their systematic use severely compromise code maintainability. Anyway, if it's the only solution, I will go for it. – Marcello Mar 31 '16 at 16:02

0 Answers0