Reputation: 3391
I keep a bunch of objects of the below structure in a MongoDB collection. I try to resketch the most important points sort of pseudo-code like, and hopefully no elementary functions are missing to understand my question:
public class O {
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public int c { get; set; }
[BsonElement]
[BsonDateTimeOptions(DateOnly = true)]
public DateTime date { get; set; }
}
Through an ASP.NET Core controller class, in comes a request to find an object by date:
public class Contrl : ControllerBase {
private readonly OService _oserv;
[HttpGet]
public ActionResult<O> GetByDate([FromQuery] int c, [FromQuery] DateTime date) {
_oserv.GetByDate(c, date);
}
}
The service then connects to the database and submits the query (LINQ) and uses a helper method (IsSameDate
) to check if the dates match:
public class OService {
private readonly IMongoCollection<O> _repo;
public List<O> GetByDate(int c, DateTime date) {
O searchResult = _repo.Find<O>(o => IsSameDate(o.date, date).FirstOrDefault();
}
public bool IsSameDate(DateTime d1, DateTime d2) =>
d1.Year == d2.Year && d1.Month == d2.Month && d1.Day == d2.Day;
}
I receive a HTTP 500 error and in the error message it says:
System.ArgumentException: Unsupported filter:
value(proj.Services.OService).IsSameDate({document}{date}, 20/02/2020 00:00:00).
So it looks like it’s going in the right direction, but it doesn't use o.date
in the helper method. Instead it uses {document}{date}
. What is that and how can I do this correctly?
Upvotes: 0
Views: 129
Reputation: 20980
If you want to filter by Date Only then there is the below way:
First you have to create two Date's like below,
public List<O> GetByDate(int c, DateTime date) {
var startDate = new DateTime(date.Year, date.Month, date.Day);
var endDate = startDate.AddDays(1);
var filter = Builders<O>.Filter.Gte(x => x.date, startDate)
& Builders<O>.Filter.Lt(x => x.date, endDate);
//Note: Get your Collection before this line and then use it.
O searchResult = await Collection.Find(filter).FirstOrDefaultAsync();
}
Upvotes: 1