Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda