<?xml version="1.0" encoding="utf-8"?><rss version="2.0"><channel><title>RavenDB</title><link>http://timlabonne.com:80/ravendb-2</link><description>RavenDB</description><item><title>RavenDB Survival Tip #2: Simulating select count(*)</title><link>http://timlabonne.com:80/2013/07/ravendb-survival-tip-2-simulating-select-count/</link><description>&lt;p&gt;A lot of the time a user will ask for a count of some business entity on a report so they can tell how many of something is happening.&amp;nbsp; With SQL, this is a very natural process with aggregate operations:&lt;/p&gt;&lt;pre class="brush: sql;"&gt;select count(*) from Users where IsAdmin = true
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;But with RavenDB, I found it difficult to wrap my mind around how you would do this with an Index.&amp;nbsp; Aggregate operations like this are implemented with map/reduce indexes.&amp;nbsp; Since the reduce step of the index needs to have the same output shape as the map, we can’t simply return a single numeric value as is the case with SELECT COUNT(*) in SQL.&amp;nbsp; We need to perform a LINQ group-by.&amp;nbsp; But in this case, I don’t really want to group by anything in a document, I just want a count.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;After a little thinking and digging around, I found a solution.&amp;nbsp; Maybe this is obvious to most, but I found that if we simply group by a constant, we can get a single numeric value for that constant the represents the total count.&lt;/p&gt;
&lt;p&gt;Here’s a sample Index definition that demonstrates this concept.&amp;nbsp; In the Index, I am trying to find all User documents that qualify as admins (IsAdmin = true).&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;public class Users_AdminCounts : AbstractIndexCreationTask&amp;lt;User, Users_AdminCounts.ReduceResult&amp;gt;
{
    public class ReduceResult
    {
        public string Name { get; set; }
        public int Count { get; set; }
    }

    public Users_AdminCounts()
    {
        // the Name parameter to the reduce function is dummy
        // to get it to aggregate to one single value
        Map = users =&amp;gt;
            from user in users
            where user.IsAdmin = true
            select new { Name = "Total", Count = 1 };

        Reduce = results =&amp;gt;
            from result in results
            group result by result.Name
            into g
            select new { Name = g.Key, Count = g.Sum(x =&amp;gt; x.Count) };
    }
}
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;When you run the query and get the result (ReduceResult), you will get just one single result and the Count property will contain the count aggregate you are looking for.&lt;/p&gt;</description><pubDate>Wed, 10 Jul 2013 19:00:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/2013/07/ravendb-survival-tip-2-simulating-select-count/</guid></item></channel></rss>