过滤mongodb数据收集过滤器

时间:2019-06-22 12:34:07

标签: c# mongodb filtering driver

我在后端使用了mongodb来存储一些客户的个人信息,并且需要获取30、32和35岁的用户。

我尝试了以下获取方法,但返回的结果为零,我使用了C#MongoDB.Driver

C#代码

Age = new string[] { "26-30", "31-35" }
DateTime today = DateTime.Today;
var filter = Builders<Customer>.Filter.Empty;
foreach (var item in searchFilterBlock.Age)
 {
    var ageBetween = item.Split('-');
    int.TryParse(ageBetween[0], out int startYear);
    int.TryParse(ageBetween[1], out int endYear);
    var start = today.AddYears(-startYear);
    var end = today.AddYears(-endYear); 
    filter = filter & (Builders<Customer>.Filter.Gte(x => x.Dob, start)
                        & Builders<Customer>.Filter.Lte(x=>x.Dob, end));
 }
// to execute the filter
var searchResult = _context.Customer.Find(filter).ToList(); // it return 0 result

需要确定30、32和35岁的人。

1 个答案:

答案 0 :(得分:0)

您可以使用如下所示的$or过滤器来获得30、32和35岁的客户:

db.Customer.find({
    "$or": [
        {
            "DOB": {
                "$lte": ISODate("1989-06-22T14:57:50.168Z"),
                "$gte": ISODate("1988-06-22T14:57:50.168Z")
            }
        },
        {
            "DOB": {
                "$lte": ISODate("1987-06-22T14:57:50.168Z"),
                "$gte": ISODate("1986-06-22T14:57:50.168Z")
            }
        },
        {
            "DOB": {
                "$lte": ISODate("1984-06-22T14:57:50.168Z"),
                "$gte": ISODate("1983-06-22T14:57:50.168Z")
            }
        }
    ]
})

这是使用便捷库MongoDB.Entities生成上述查找查询的c#代码[免责声明:我是作者]

using MongoDB.Driver;
using MongoDB.Entities;
using System;
using System.Collections.Generic;

namespace StackOverflow
{
    public class Program
    {
        public class Customer : Entity
        {
            public string Name { get; set; }
            public DateTime DOB { get; set; }
        }

        private static void Main(string[] args)
        {
            new DB("test");

            (new[] {
                new Customer{ Name = "I am 29", DOB = DateTime.UtcNow.AddYears(-29)},
                new Customer{ Name = "I am 30", DOB = DateTime.UtcNow.AddYears(-30)},
                new Customer{ Name = "I am 32", DOB = DateTime.UtcNow.AddYears(-32)},
                new Customer{ Name = "I am 35", DOB = DateTime.UtcNow.AddYears(-35)},
                new Customer{ Name = "I am 36", DOB = DateTime.UtcNow.AddYears(-36)}
            }).Save();

            var ages = new[] { 30, 32, 35 };

            var filters = new List<FilterDefinition<Customer>>();

            foreach (var age in ages)
            {
                var start = DateTime.UtcNow.AddYears(-age);
                var end = DateTime.UtcNow.AddYears(-age - 1);
                filters.Add(DB.Filter<Customer>()
                              .Where(c => c.DOB <= start && c.DOB >= end));
            }

            var customers = DB.Find<Customer>()
                              .Many(f => f.Or(filters))
                              .ToArray();
        }
    }
}