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", ...] }
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" ] }