0

does anybody know to to search in nested array using c# driver for mongodb ?

For example: I have a list of documents of type Person. An example of Person entity is the following

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

How can i write a query that will bring me all the documents with Occupation Student, Class Math and Professor Smith ?

I tried with elemMatch something like the following but it doesn't work

        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

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.