Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

Window query (get before and after)

Hi i have sorted collection by EntryDate:

{
  "_id" : "5e4a8e13b0b2ddcad37fa308",
  "EntryDate" : ISODate("2020-02-17T12:59:00.023Z"),
  "Text" : "randomtext"
}

I know EntryDate point. I need take 5 items before and 5 items after this point. Now i do 2 query, can in optimization to 1 query?

var top  =  col.Find(c.EntryDate < point).SortByDescending(c => c.EntryDate).Limit(5);
var down =  col.Find(c.EntryDate > point).Sort(c => c.EntryDate).Limit(5);
var result = top.Concat(down);

You can try using the $facet aggregation. This allows multiple sub-pipelines (two in this case - one for before and the other for after) and then combine as one result within the same aggregation.

1 Like

good variant . but…
what other ideas?

What (but)? Any concerns or issues.? It helps to think further if you are a bit more specific.

mb mongodb not for this case ?
because for hiload such request looks strange