如何使用C#驱动程序在mongodb嵌套数组中搜索

时间:2019-02-26 17:50:09

标签: c# arrays mongodb nested

有人知道要使用c#驱动程序对mongodb进行嵌套数组搜索吗?

例如: 我有一个Person类型的文档列表。以下是一个Person实体的例子

 {
    "Name": "HumanName",
    "Occupation": "Student",
    "Class": [
        {
            "ClassType": "Math",
            "Professors": [
                {
                    "Name": "Jimmy"
                },
                {
                    "Name": "Smith"
                }
            ]
        },
        {
            "ClassType": "English",
            "Professors": [
                {
                    "Name": "John"
                }
            ]
        }
    ]
}

我该如何编写一个查询,将职业学生,数学班和史密斯教授的所有文档带给我?

我尝试使用elemMatch进行以下操作,但它不起作用

        var builder = Builders<Person>.Filter;
        var filters = builder.Eq(x => x.Occupation, "Student");

        filters = filters & builder.ElemMatch(x => x.Class, x=> x.ClassType =="Math");
        filters = filters & builder.ElemMatch(x => x.Class[-1].Professors, x=> x.Name =="Smith");

        var result = await Mongo.Persons.Find(filters).SingleOrDefaultAsync();

1 个答案:

答案 0 :(得分:0)

var collection = database.GetCollection<Person>("Person");
var list = collection.AsQueryable()
            .Where(x => x.Ocupation == "Student" 
                     && x.Class.Any(y => y.ClassType == "Math" 
                     && y.Proffessors.Any(z => z.Name == "Smith")))
            .ToList();