I’m not able to load just one element of an array at a lower level on mongodb

Asked

Viewed 42 times

2

Person I’m trying to pull just one helper, I’m doing the following,

db.colecao.find( { functio.nome : joão }, { 'functionary.helper. $' 1 } );

but always comes everyone, I’ve tried several ways, Bs there in helper could have much more and dynamic

{
    empresa : 'nome da empresa',
    funcionario : [
        {
            nome : 'joão',
            ajudante : [
                {
                    nome : manoel,
                    idade : 24
                },
                {
                    nome : joel,
                    idade : 20
                }
            ]
        }
    ]
}
  • 1

    I think it would be interesting to explain a little better, this vague bemmmm

  • I’m only trying to pull one helper Since you will have more than two and I’m sorry for the spelling and coding errors this and only one example I’m doing the following, db.colecao.find( { funcio.name : Jõao }, { 'funcio.helper.$' : 1 } ); , but it always comes all, I’ve tried it in many ways

1 answer

0

From what I understand you want to return only the helpers(s) of some employee.

find will always return a document from Collection, returning the document and the structure to support your projection. If you run this query:

db.teste.find(
     {"funcionario.nome": "joão", "funcionario.ajudante.nome": 'manoel'}, 
     {"funcionario.ajudante.nome": 1}
)

The return will include the array with all elements, but showing only the name of each helper. This is because in the query you are asking for a document that has an employee with name "john", that has a helper with name "Manoel".

If you want to return only the helper in question, you need to use an aggregation:

db.teste.aggregate(
    {$match: {"funcionario.nome" : "joão"}}, 
    {$project: {"funcionario.nome" : 1, "funcionario.ajudante" : 1}}, 
    {$unwind: "$funcionario"}, 
    {$unwind: "$funcionario.ajudante"},
    {$match: {"funcionario.ajudante.nome" : "manoel"}}
)

If you are going to get helpers from someone who knows how often it is worth putting them in a separate Collection, and save only the names or _id in an array within the employee.

Most important: It makes no sense to keep the company, its employees and helpers in a document only if you don’t want to recover it at once from the bank.

Gives a research on modeling in Mongo, the most important thing is to think how you will access/modify the data.

  • thank you very much friend

  • You are welcome! Please mark the question as answered to make it clear to someone who is searching.

  • I’m new here as I do rss

  • Take a look here: https://answall.com/help/someone-answers :)

Browser other questions tagged

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