Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying child collections within a Ravendb document

Tags:

c#

nosql

ravendb

Say I have a blog with a collection of posts, and each post has a collection of comments. I want to query all the comments to find the 5 most recent across all blog posts. With an RDBMS you simply go straight for the comments table, sort by date and take 5. Is it possible to do something similar within Ravendb, given that comments aren't the aggregate root?

like image 747
edgarian Avatar asked Feb 22 '12 23:02

edgarian


2 Answers

highace, Yes, you can certainly do that. You can see how we do something similar here: https://github.com/ayende/RaccoonBlog/blob/master/RaccoonBlog.Web/Infrastructure/Indexes/PostComments_CreationDate.cs

like image 83
Ayende Rahien Avatar answered Oct 07 '22 01:10

Ayende Rahien


It makes sense to store your comments as seperate documents rather than in each post otherwise you end up loading and saving the entire post document every time a comment is added.

With this in mind you would simply query your comments something like the following

session.Query<Comment>().OrderByDescending(x => x.CommentDate).Take(5)
like image 42
Scott Mackay Avatar answered Oct 07 '22 02:10

Scott Mackay