Search code examples
c#mongodbmongodb-.net-driverfluent-mongo

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 comments along with my Post data.

  1. What's the best way of doing this?
  2. 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.


Solution

  • 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) { 
        ...
    }