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

168
Visualizações
Get an array of values of a field in MongoDB

I have some entries like:

{ "name":"a", "value":10 }
{ "name":"b", "value":20 }
{ "name":"c", "value":10 }
...

And I can select names from a query with db.collection.find({"value":10},{"name":1, _id: false}). It gives me the following:

{ "name" : "a" }
{ "name" : "c" }
...

However, I want it to return an array of values, not a set of { key : value } pairs. (like [ "a", "c", ... ]). Is there a way to achieve this with only MongoDB queries or should I select and put them in an array in my application?

Current Output:

{ "name" : "a" }
{ "name" : "c" }
...

Expected output:

["a", "c", ...]

If the above is not a possible output, it may be also

{ "result": ["a", "c", ...] }
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

db.collection.distinct( "name", { "value": 10 })

from @Sagar Reddy comment will return a set array:

["a", "c"]

This is probably what you need. Aniway, a similar more complex query can be achieved using aggregation, where you can use extra aggregation stages.

db.collection.aggregate([
    { $match: { value: 10 }},
    { $group: { _id: null, result: { $addToSet: '$name' }}}, 
    { $project: { _id: 0, result: 1 }}
])

In the group stage, addToSet can be replaced with push if you want the same value to appear multiple times.

Output using addToSet:

{ "result" : [ "c", "a" ] }

Ex output using push:

{ "result" : [ "a", "c", "c" ] }
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