Reputation: 11155
I have a collection with DateTime
in it.
public class Trade
{
public ObjectId Id { get; set; }
public DateTime Expiary { get; set; }
}
I am using the c# driver, and I want to get the closest Expiry from the Trade
collection.
Is possible in mongodb to bring the closest dates to a given date?
Update
something like
collection.FindClosest(x => x.Expiary , DateTime.Now.AddDays(-1))
Upvotes: 2
Views: 550
Reputation: 6398
If I understand correctly, "closest date" could be considered like:
var record = tests.Find(p => p.Date <= closestTo)
.SortByDescending(p => p.Date)
.FirstOrDefault();
Surely there could be a document with a date 'closer' to what you are looking for at a higher bound, but 'future' to your filter, in which case you would skip and fetch the closest older. If your requirement really demands you get that item, I must say I'm unaware of a 'Mongo way' in doing that. It could be done by running this query twice, the second time with the order inverted (and .Date > closestTo) and verify in-process which of the two objects is the closest.
Upvotes: 2