How do I write an index to get the total number of objects in a collection across documents in RavenDB?

StackOverflow https://stackoverflow.com/questions/21174002

  •  28-09-2022
  •  | 
  •  

Question

I have the following object that I'm saving as a document in my database:

public class ClientContactsModel
{
    public ClientContactsModel()
    {
        Contacts = new List<ContactItem>();
    }

    public Guid Id { get; set; }
    public Guid ClientId { get; set; }
    public List<ContactItem> Contacts { get; set; }
}

How would I write an index to count the number of contacts in each of the ClientContactsModel objects to get a total number of contacts?

Was it helpful?

Solution

I was able to figure this one out:

public class Contacts_GetCount: AbstractIndexCreationTask<ClientContactsModel, Contacts_GetCount.ContactResult>
{
    public class ContactResult
    {
        public Guid ClientId { get; set; }
        public int Total { get; set; }
    }

    public Contacts_GetCount()
    {
        Map = contacts => from contact in contacts
            select new {
                ClientId = contact.ClientId,
                Total = contact.Contacts.Count
            };

        Reduce = results => from result in results
            group result by result.ClientId
            into g
            select new {
                ClientId = g.Key,
                Total = g.Sum(x=>x.Total)
            };
    }
}

The piece I was missing was putting the count of the collection in the created anonymous type in the mapping of the document.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top