I am not able to load only one element of an array at a lower level in mongodb

2

Person I'm trying to pull just a helper, I'm doing the following,

db.colecao.find (     {official.name: John}     {'official.helper. $': 1} );

But everyone always comes, I've tried in many ways, obs in helper could be much more dynamic

{
    empresa : 'nome da empresa',
    funcionario : [
        {
            nome : 'joão',
            ajudante : [
                {
                    nome : manoel,
                    idade : 24
                },
                {
                    nome : joel,
                    idade : 20
                }
            ]
        }
    ]
}
    
asked by anonymous 07.08.2017 / 22:21

1 answer

0

So I understand you want to return only the helpers of some employee.

The find will always return a document from the 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 named "john", who has a helper named "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 go get someone's helpers often who knows it's worth putting them in a separate collection, and save only the names or _id in an array inside the employee.

Most important : It does not make sense for you to save your company, your employees and helpers in a document only if you do not want to recover it at one time from the bank.

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

    
10.08.2017 / 15:06