Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!