3

When searching a collection on some field, I can specify that I only want returned certain fields. In the case of only returning one field, let's say "_id", the find command returns an array of key:value pairs [ {_id:123}, {_id:234}, {_id:345} ] Is there any way to have find return an array of values only? As in: [123, 234, 345]

I can massage the returned array on my own, but if it's possible for mongodb to do this for me, then I'd rather have it do so.

1 Answer 1

4

In order to get that kind of output, you'd have to use the aggregation framework. And even with the aggregation framework, the best you could get would be:

{ values: [ 123, 234, 345 ] }

You'd essentially have to use $group to get all of your values together. Something like this:

db.collectionName.aggregate({
    $group: {
        values: { $push: "$_id" }
    }
});

I'm not sure if you'd need an _id for group, but if the above doesn't work, you could just add that. I'm not sure if that would be any faster than just massaging it after you return the search.

Sign up to request clarification or add additional context in comments.

2 Comments

Based on the above answer, it seems that I might as well massage it on my own. Thanks.
Unfortunately, that's true. You can only get documents back from Mongo.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.