2

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", ...] }
4
  • Use $in
    – Neo-coder
    Commented Jan 2, 2017 at 8:11
  • But how? Where to put it in this query? Commented Jan 2, 2017 at 8:13
  • It's still confusing, can you add your expected output
    – Neo-coder
    Commented Jan 2, 2017 at 8:37
  • 2
    You can try db.collection.distinct( "name", { "value": 10 })
    – s7vr
    Commented Jan 2, 2017 at 8:57

1 Answer 1

4
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" ] }
2
  • The output of this query gives { "result" : [ { "result" : [ "c", "b" ] } ], "ok" : 1 }. How can I make it just { "result" : [ "c", "b" ] }? Commented Jan 2, 2017 at 10:17
  • 1
    It is extra aggregation output information, you will always get that in return from your driver, that is the first result key which holds the aggregation result. The second result key which holds the array is the key that you define in the aggregation stages. Just acces the key inside the dict: actualResult = aggregationResult['result']
    – sergiuz
    Commented Jan 2, 2017 at 10:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.