25

I would like to run following query:

Group.find({program: {$in: [...]}}).lean().select('_id')

And then NOT get following back:

[{_id: ...}, {_id: ...}, {_id: ...}, {_id: ...}]

BUT following:

[..., ..., ..., ...] 

where ... represents an _id of a Group.

Of course I could just run the query and then loop through the Groups I get back, but I would like to do it in the query if possible, because that's probably going to be faster.

2 Answers 2

57
Group.find({program: {$in: [...]}})
  .distinct('_id')

db.collection.distinct(field, query)

Finds the distinct values for a specified field across a single collection and returns the results in an array.

Read more.

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

3 Comments

Thank you, I will try that tomorrow!
Why do you have lean() in it the distinct will only return the ids?
@ElishaSterngold I agree, it's certainly redundant - thanks for noticing, I updated my answer to reflect that.
0

You can also pass the query directly into a distinct() call:

Group.distinct('_id', {program: {$in: [...]}})

which would return an array of ObjectIds satisfying the query.

Comments

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.