4

我在查询 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 查询文档并过滤一些地址值以返回名称为 %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();

使用版本:

  • MongoDB.Driver v 2.6.1(也是 Bson)
  • .Net 框架 4.5.2
4

1 回答 1

7

这应该可以帮助您:

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();
于 2018-06-18T08:41:43.280 回答