5

I have a need to get a Count of Documents in a particular collection :

There is an existing index Raven/DocumentCollections that stores the Count and Name of the collection paired with the actual documents belonging to the collection. I'd like to pick up the count from this index if possible.

Here is the Map-Reduce of the Raven/DocumentCollections index :

from doc in docs
let Name = doc["@metadata"]["Raven-Entity-Name"]
where Name != null
select new { Name , Count = 1}

from result in results
group result by result.Name into g
select new { Name = g.Key, Count = g.Sum(x=>x.Count) }

On a side note, var Count = DocumentSession.Query<Post>().Count(); always returns 0 as the result for me, even though clearly there are 500 odd documents in my DB atleast 50 of them have in their metadata "Raven-Entity-Name" as "Posts". I have absolutely no idea why this Count query keeps returning 0 as the answer - Raven logs show this when Count is done

Request # 106: GET     -     0 ms - TestStore  - 200 - /indexes/dynamic/Posts?query=&start=0&pageSize=1&aggregation=None
Zasz
  • 12,330
  • 9
  • 43
  • 63

2 Answers2

10

For anyone still looking for the answer (this question was posted in 2011), the appropriate way to do this now is:

var numPosts = session.Query<Post>().Count();
casperOne
  • 73,706
  • 19
  • 184
  • 253
Jay Querido
  • 1,257
  • 1
  • 12
  • 15
5

To get the results from the index, you can use:

session.Query<Collection>("Raven/DocumentCollections")
       .Where(x=>x.Name == "Posts")
       .FirstOrDefault();

That will give you the result you want.

Zasz
  • 12,330
  • 9
  • 43
  • 63
Ayende Rahien
  • 22,925
  • 1
  • 36
  • 41
  • This helped me a lot thanks, I was trying to use : from Collection collection in session.Query("Raven/DocumentCollections") where collection.Name = "Posts" select collection.Count and hitting various errors. – Zasz Apr 17 '11 at 08:24
  • WORKS : var Count = DocumentSession.Query("Raven/DocumentCollections").Where(X => X.Name == "Posts").FirstOrDefault().Count; NOT WORKS : var Count = (from collection in DocumentSession.Query("Raven/DocumentCollections") where collection.Name == "Posts" select collection.Count).First(); throws a NullReferenceException in at Raven.Client.Document.AbstractDocumentQuery`2.Deserialize(JObject result) in c:\Builds\raven\Raven.Client.Lightweight\Document\AbstractDocumentQuery.cs:line 1262 and .. – Zasz Apr 17 '11 at 12:22
  • 4
    "Collection" is defined where? – nathanchere Mar 17 '12 at 04:54