MongoDB中/ C#过滤器,并得到所有的子文档(MongoDb / C# filter and

2019-10-29 09:08发布

我有一个查询蒙戈-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"
        }
        ]
}

我现在想查询由客户编号的文件,并筛选某些地址值的与喜欢%丹%一个名称返回的所有地址。 由于地址收集可以是巨大的我想已经过滤在查询时这些地址

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"
        }
        ]
}

我也试过几种方法与骨料/匹配/项目,但不能让它开始工作。 “AsQueryable已”也可作为的IndexOf未在驱动程序中实现不起作用。

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

二手版本:

  • MongoDB.Driver v 2.6.1(也BSON)
  • .Net框架4.5.2

Answer 1:

这应该让你去:

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
    }
}])

对于不区分大小写的版本,会有一个使用正则表达式$在某个阶段在未来(见选项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();


文章来源: MongoDb / C# filter and get all subdocuments