Chad Moran
Chad Moran

Reputation: 12854

How to get aggregate data of embedded document properties in RavenDB

I have a model that looks something like this

public class User
{
    public List<Action> Actions { get; set; }
}

public class Action
{
    public DateTime CreatedOn { get; set; }
}

I'm trying to find a way to get the maximum value of CreatedOn from all actions across all users.

I'm new to RavenDB and I'm not sure if I should use a Map/Reduce or what.

Upvotes: 1

Views: 252

Answers (1)

Daniel Lang
Daniel Lang

Reputation: 6839

Here is a complete sample:

public class User
{
    public string Id { get; set; }
    public List<Action> Actions { get; set; }
}

public class Action
{
    public DateTime CreatedOn { get; set; }
}

public class ActionCreatedOnResult
{
    public DateTime CreatedOn { get; set; }
}

public class Users_ActionCreatedOn : AbstractIndexCreationTask<User, ActionCreatedOnResult>
{
    public Users_ActionCreatedOn()
    {
        Map = users => from user in users
                       from action in user.Actions
                       select new
                                  {
                                      action.CreatedOn
                                  };
        Store(x => x.CreatedOn, FieldStorage.Yes);
    }
}

class Program
{
    static void Main(string[] args)
    {
        using (var documentStore = new DocumentStore{ Url = "http://localhost:8080/" })
        {
            documentStore.Initialize();

            IndexCreation.CreateIndexes(typeof(Users_ActionCreatedOn).Assembly, documentStore);

            using (var documentSession = documentStore.OpenSession())
            {
                var result = documentSession.Query<ActionCreatedOnResult, Users_ActionCreatedOn>()
                    .OrderByDescending(x => x.CreatedOn)
                    .AsProjection<ActionCreatedOnResult>()
                    .FirstOrDefault();
            }
        }
    }
}

Upvotes: 4

Related Questions