Query return specific array of mongodb documents

0

I have the following document called "COURSE":

{
    "_id" : ObjectId("58a300ff3de08a3cdce471be"),    
    "nome" : "Matemática",
    "turma" : [ 
        {
            "professor" : {
                "nome" : "Maria",
                "usuarioId" : ObjectId("58a2f129c685a21b88ccee84")
            },
            "aluno" : [ 
                {
                    "nome" : "Pedro",
                    "usuarioId" : ObjectId("58a2f208c685a21b88ccee86")
                }, 
                {
                    "nome" : "Marcio",
                    "usuarioId" : ObjectId("58a723964530540a70e2b37b")
                }
            ],
            "_id" : ObjectId("58a3035e503e932c909553ea"),
            "turno" : "Matutino",
            "nome" : "Matemática 1"
        }, 
        {
            "_id" : ObjectId("58a3036c503e932c909553eb"),
            "professor" : {
                "nome" : "João",
                "usuarioId" : ObjectId("58a2f129c685a21b88ccee84")
            },
            "aluno" : [ 
                {
                    "nome" : "José",
                    "usuarioId" : ObjectId("58a2f208c685a21b88ccee86")
                }
            ],            
            "turno" : "Noturno",
            "nome" : "Matemática 2"
        }
    ]    
}

I'm trying to make a query that returns only the classes that a certain student is inserted, but my query is returning all classes, even the student being part of only one of the classes in this course, an example of how the consultation is being done :

db.getCollection('cursos').find(    
    { turma: { $elemMatch: { 'aluno.usuarioId': ObjectId("58a723964530540a70e2b37b") } } }
)

The result of this query it ends up bringing the classes "Mathematics 1" and "Mathematics 2", I would like to know if you have a query that returns only the classes that the student is part of.     

asked by anonymous 10.03.2017 / 19:22

1 answer

0

You can use $elemMatch in projection too:

db.getCollection('cursos').find(
  {turma: {$elemMatch: {'aluno.usuarioId': ObjectId("58a723964530540a70e2b37b")}}},
  {turma: {$elemMatch: {'aluno.usuarioId': ObjectId("58a723964530540a70e2b37b")}}, nome: 1},
)

See more about projection with $elemMatch here .

    
13.03.2017 / 20:09