[英]How to find an entry in a Mongo Collection through C# driver by DateTime?
I keep a bunch of objects of the below structure in a Mongo collection.我在 Mongo 集合中保留了一堆具有以下结构的对象。 I try to resketch the most important points sort of pseudo-code like, 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, comes in a request to find an object by date:通过 ASP.NET 内核 controller class 请求找到一个 ZA8CFDE6331BD59EB66AC96F891111C4 日期:
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 DB and submits the query (LINQ) and uses a helper method ( IsSameDate
) to check if the dates match:然后该服务连接到数据库并提交查询 (LINQ) 并使用辅助方法 ( IsSameDate
) 检查日期是否匹配:
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:我收到 HTTP 500 错误,并在错误消息中显示:
System.ArgumentException: Unsupported filter:
value(proj.Services.OService).IsSameDate({document}{date}, 20/02/2020 00:00:00).
So it looks like its 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 to do this correctly?所以看起来它朝着正确的方向前进,但它没有在辅助方法中使用o.date
,而是使用{document}{date}
,那是什么以及如何正确地做到这一点?
If you want to filter by Date Only then there is below way:如果您想仅按日期过滤,则有以下方法:
First you have to create two Date 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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.