首页 > 解决方案 > 如何使用 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);
                        }
                    }
                }
            }

标签: c#mongodb

解决方案


使用 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 将是您要比较的字段。

以此为例:https ://github.com/vpaulino/VPFrameworks/blob/master/src/VPFrameworks.Persistence.MongoDb/MongoDbRepository.cs


推荐阅读