MongoDb / C#过滤并获取所有子文档

MongoDb / C# filter and get all subdocuments

我在查询 Mongo-DB 集合时遇到困难。

我正在使用的文档

public class Customer
{
    public ObjectId Id { get; set; }

    public int CustomerId { get; set; }

    public List<Address> Addresses { get; set; }
}

public class Address
{
    public string Name { get; set; }
}

一些示例数据

{
    CustomerId: 2,
    Addresses: [
        {
            Name: "Daniel"
        },
        {
            Name: "Eric"
        },
        {
            Name: "Dan"
        }
        ]
}

我现在想通过 CustomerId 查询文档并将一些地址值过滤为 return 所有名称如 %Dan% 的地址。由于地址集合可能很大,我想在查询时过滤这些地址

var mdb = mongoClient.GetDatabase("test");
var collection = mdb.GetCollection<WebApi>("Customer");
var builder = Builders<Customer>.Filter;
var searchTerm = "Dan";

当这样查询时它有效但它包含所有地址:

var filter = builder.And(builder.Eq("InstallationId", 2),
                         builder.Regex("Addresses.Name", new BsonRegularExpression(".*" + searchTerm + ".*", "i")))
var result = collection.Find(filter).FirstOrDefault();

我想得到的是:

[
    {
        Name: "Daniel"
    },
    {
        Name: "Dan"
    }
]

{
    CustomerId: 2,
    Addresses: [
        {
            Name: "Daniel"
        },
        {
            Name: "Dan"
        }
        ]
}

我也用 Aggregate/Match/Project 尝试了几种方法,但无法使它起作用。 "AsQueryable" 也不起作用,因为 IndexOf 未在驱动程序上实现。

collection.AsQueryable().Where(x => x.CustomId == 2).SelectMany(x =>
                x.Addresses.Where(a => a.Name.IndexOf(searchTerm, StringComparison.InvariantCultureIgnoreCase) >= 0).ToList();

使用的版本:

这应该让你继续:

var result = collection
    .Aggregate()
    .Match(c => c.CustomerId == 2)
    .Project(c => new
        {
            c.CustomerId,
            Addresses = c.Addresses.Where(a => a.Name.IndexOf(searchTerm) != -1)
        })
    .ToList();

驱动程序会将其翻译成:

db.Customer.aggregate([{
    $match: { CustomerId: 2 }
}, {
    $project: {
        CustomerId: "$CustomerId",
        Addresses: {
            $filter: {
                input: "$Addresses",
                as: "a",
                cond: {
                    $ne: [ { $indexOfBytes: [ "$$a.Name", "Dan" ] }, -1 ]
                }
            }
        },
        _id: 0
    }
}])

对于不区分大小写的版本,将来的某个阶段将有一个使用 $regex 的选项(参见 https://jira.mongodb.org/browse/SERVER-11947)。但是,您现在可以做的是使用 ToUpper():

var result = collection
    .Aggregate()
    .Match(c => c.CustomerId == 2)
    .Project(c => new
        {
            c.CustomerId,
            Addresses = c.Addresses.Where(a => a.Name.ToUpper().IndexOf(searchTerm.ToUpper()) != -1)
        })
    .ToList();