-->

Raven DB Count Queries

2020-07-13 10:41发布

问题:

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

回答1:

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.



回答2:

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

Hope this helps...



标签: ravendb