Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

195
Visualizações
Get Specific Values from MongoDB

I am new to Mongo so any help is appreciated.

I have a User object and in it multiple more objects which are hosting client data based on the User's interaction with each one.

This is how it looks like

db.users.findOne(
  {"clients.clientId":35},
  {"clients.clientId":1}
)
{
  "_id" : ObjectId("586670e6ce9287cf6d197d14"),
  "clients" : [ 
        { "clientId" : 35 },
        { "clientId" : 67 }, 
        { "clientId" : 73 }, 
        { "clientId" : 78 }, 
        { "clientId" : 82 } 
  ] 
}

As you can see from my query, it returns a User that has data from client 35 but also returns data from every other client.

How can I access only the data from client 35?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You have an embedded array of documents on the clients key.

Your query projection {"clients.clientId":1} states that the query should return only that key, clients key. Your clients field is an array, therefore all embedded documents from the array will be extracted (projected).

When you want only one element in the array to be displayed, the one defined in the query i.e. the client with id 35 {"clients.clientId":35}, need to use the projection positional operator $:

db.users.findOne({"clients.clientId":35},{"clients.$":1})

Result:

{
    "_id" : ObjectId("586670e6ce9287cf6d197d14"),
    "clients" : [
        {
            "clientId" : 35
        }
    ]
}

Note: using $ operator, it will project only the first element in the array that matches the query; if you have more documents in the array having the same value, only the first will be displayed.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda