c# - 如何使用 BsonDocument 按日期过滤文档
问题描述
我正在使用 BsonDocument 从 mongDB 获取文档。我需要添加多个条件来做到这一点。
我添加了一个过滤器,我需要另一个过滤器来获取最新数据(过去 7 天)
我正在尝试添加以下代码但不知道如何设置条件
List<TestDataObject> returnResult = new List<TestDataObject>();
BsonDocument filter = new BsonDocument();
Links links = new Links();
try
{
filter.Add("EvaluationComplete", new BsonBoolean(isEvaluated));
filter.Add("DateRunUtc", new BsonDateTime(DateTime.Now.AddDays(-7)),condition);
var options = new FindOptions<BsonDocument>()
{
Skip = skip,
Limit = limit
};
long count = await _testResultCollection.CountDocumentsAsync(filter);
links = GetHATEOAS(count, skip, limit, hateoasUrl, "TestResult");
using (var cursor = await _testResultCollection.FindAsync(filter, options))
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (BsonDocument document in batch)
{
TestDataObject testData = BsonSerializer.Deserialize<TestDataObject>(document);
testData.Self = self + "/self?id=" + testData.Id;
returnResult.Add(testData);
}
}
}
}
解决方案
使用 MongoDb,您还可以将一些强类型关联到每个集合并使用 MongoDb 查询 API。对于您的示例,您可以执行以下操作:
FilterDefinitionBuilder<TEntity> filterBuilder = new FilterDefinitionBuilder<TEntity>();
var dateIntervalQuery = filterBuilder.And(filterBuilder.Gte<DateTime>((entity) => entity.Created, CreatedBiggerThen), filterBuilder.Lte<DateTime>((entity) => entity.Created, CreatedlessThen));
您的 TEntity 有一段时间需要有一些日期字段的约束。CreatedLessThen 和 CreatedBiggerThen 将是您要比较的字段。
推荐阅读
- python - 使用python为xml文件中的子元素缩进
- mailgun - Mailgun:电子邮件转发不起作用?
- php - 从本地文件系统复制文件并处理到另一台服务器的数据库中
- android - Xamarin Android:接收 Firebase 通知令牌
- java - 任务 ':query-api:compileJava' 的 Gradle 执行失败。
- javascript - 给定一个随机值数组,计算缺少哪些值以及其中有多少?
- javascript - 将音频文件从 Angular 资产发布到服务器
- c# - 如何将 XML 从 ASP.NET 4 Web API 返回到 ASP.NET Core 2 应用程序?
- wkwebview - WKWebView 无法从 https://mobile.bet365.com 加载整页
- c# - WPF 应用程序不会使用 Application.Run() 打开;