如何在RavenDB中获取嵌入文档属性的聚合数据

时间:2011-11-18 03:54:15

标签: c# ravendb

我有一个看起来像这样的模型

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

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

我正试图找到一种方法,从所有用户的所有操作中获取CreatedOn最大值。

我是RavenDB的新手,我不确定是否应该使用Map / Reduce或者是什么。

1 个答案:

答案 0 :(得分:4)

以下是完整的示例:

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();
            }
        }
    }
}