C# & Mongodb - How to filter in child document?

Asked

Viewed 235 times

0

I am starting my adventures in Mongodb and I have a problem specifically with the filtering of documents. The model of my application:

public class MatrizCurricular
{
    [BsonId]     
    public ObjectId _id { get; set; }
    public string Curso { get; set; }       
    public IList<Semestre> Semestres { get; set; }
}
public class Semestre
{
    public int NumSemestre { get; set; }     
    public IList<Disciplina> Disciplinas { get; set; }
}
public class Disciplina
{
    [BsonId]
    public ObjectId _id { get; set; }
    public string Nome { get; set; }

}

As each Matrizcurricular, has its own disciplines, I consult within it for a discipline that has the same _id

//Crio uma consulta           
var filter = Builders<MatrizCurricular>.Filter.Eq("semestres.disciplinas._id", new ObjectId(id));
//Executo a consulta
var results = bd.MatrizCurricular.Find(filter).ToList();

Upshot:

[
{
    "_id": "sdfsdfsdf",
    "curso": "Administração",
    "semestres": [
        {
            "numSemestre": 1,                
            "disciplinas": [
                {
                    "_id": "asdasdasd",
                    "nome": "Administração financeira"
                },
                {
                    "_id": "paeiutaiurt",
                    "nome": "Teoria Geral da Administração"
                },
                {
                    "_id": "ajshgdajsh",
                    "nome": "Matemática"
                }
            ]
        },
        {
            "numSemestre": 2,            
            "disciplinas": [
                {
                    "_id": "6hti7d3dt7dwht67",
                    "nome": "Macroeconomia"
                },
                {
                    "_id": "d8u9dm7or7yu4t4e6",
                    "nome": "Raciocínio lógico"
                },
                {
                    "_id": "s8ory7niw3i7hn",
                    "nome": "Teoria da organização"
                }
            ]
        }
    ]
}
]

The problem is that when I run this query, the result I have is the entire document of Matrizcurricular containing the Discipline desired, but with all other documents Discipline and Semester relatives. I can get around the situation by making a query using Linq after the data has already been brought from the bank, but this is clearly not the best option

Is there any way to bring, by a direct consultation with the bank only a document of type Discipline?

  • as would be the desired result Wender?

  • @Lucascosta something like: { "_id": "d8u9dm7or7yu4t4e6", "name": "Logical reasoning" }

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.