MongoDb querying embedded collection with filtering/ordering
Let's imagine a usual blog engine (just for example). The model would consist of Posts collection with embedded Comments "collection".
Now, I need to get only 10 recent comm开发者_JAVA技巧ents along with my Post data.
- What's the best way of doing this?
- Is this a valuable optimization? (apart from reducing network traffic)
P.S. I use official C# driver + fluent-mongo but I can give up linq for a good cause.
Couldn't you use the Slice command for retrieving a subset of the array (the last 10)? Something like:
db.posts.find({}, {comments:{$slice: -10}})
I found this on the official documentation when I had to do something similar.
Link: http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements
The easiest way I could find to use the slice command with C# is:
var your_query;
var slice = Fields.Slice("comments", -10);
var cursor = collection.Find(your_query).SetFields(slice);
foreach (var document in cursor) {
...
}
Why not use a dedicated collection of most recent comments? You'll have to perform two inserts when a comment is posted, but fetching the most recent comments is simple. Typically, you would fetch these much more often than a new comment is posted anyway.
As Steve B pointed out, this is typically a 'view' in the sense that this collection might contain slightly different information than the comments within the post collection. For example, you might want to store the post id and post name in each comment so you can display a corresponding link.
You could use a capped collection of, say 100 elements, which automatically drops old comments (i.e., implements a FIFO)
精彩评论