Query return document-specific array’s mongodb

Asked

Viewed 140 times

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 am trying to make an appointment that only returns the classes that a particular student is inserted, but my query is returning all classes, even the student is part of only one of the classes of this course, an example of how the consultation is being made:

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

The result of this consultation he ends up bringing the classes "Mathematics 1" and "Mathematics 2", I wonder if it has how to make a query that returns only the classes that the student is part of.

1 answer

0


You can use $elemMatch in the projection also:

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

Behold more about projection with $elemMatch here.

  • Perfect Hezekiah, thank you very much, worked perfectly!!.

Browser other questions tagged

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