0
votes

Using the Northwind database from RavenDB tutorial I'm trying to group orders by employee and get the most resent order for every employee.

Map:

from order in docs.Orders
select new {
    Employee = order.Employee,
    Count = 1,
    MostRecent = order.OrderedAt,
    MostRecentOrderId = order.Id
}

Reduce with nonexisting MaxBy:

from result in results
group result by result.Employee into grp
select new {
    Employee = grp.Key,
    Count = grp.Sum(result => result.Count),
    MostRecent = grp.Max(result => result.MostRecent),
    MostRecentOrderId = grp.MaxBy(result => result.MostRecent).MostRecentOrderId,
}

Reduce attempt:

from result in results
group result by result.Employee into grp
let TempMostRecent = grp.Max(result => result.MostRecent)
select new {
    Employee = grp.Key,
    Count = grp.Sum(result => result.Count),
    MostRecent = TempMostRecent,
    MostRecentOrderId = grp.First(result => result.MostRecent == TempMostRecent).MostRecentOrderId
}

However my reduce attempt returns 0 results.

Also: will RavenDB treat the Order.OrderetAt as a proper DateTime value and order them correctly?

1

1 Answers

1
votes

You need to do it like

from order in docs.Orders
select new {
    Employee = order.Employee,
    Count = 1,
    MostRecent = order.OrderedAt,
    MostRecentOrderId = order.Id
}

from result in results
group result by result.Employee into grp
let maxOrder = grp.OrderByDescending(x=>x.MostRecent).First()
select new {
    Employee = grp.Key,
    Count = grp.Sum(result => result.Count),
    MostRecent = maxOrder.MostRecent,
    MostRecentOrderId = maxOrder.MostRecentOrderId,
}