MongoDb / C# filter and get all subdocuments

前端 未结 1 805
悲&欢浪女
悲&欢浪女 2021-01-14 21:53

I\'m having difficulties querying a Mongo-DB collection.

The document I\'m using

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

    pu         


        
相关标签:
1条回答
  • 2021-01-14 22:33

    This should get you going:

    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();
    

    The driver will translate this into:

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

    For the case-insensitive version, there will be a the option to use $regex at some stage in the future (see https://jira.mongodb.org/browse/SERVER-11947). However, what you can do just now is use 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();
    
    0 讨论(0)
提交回复
热议问题