Mongoose - Get list of _ids instead of array of objects with _id
Asked Answered
C

2

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.

Caseate answered 6/6, 2015 at 1:3 Comment(0)
T
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.

Turncoat answered 6/6, 2015 at 7:0 Comment(3)
Thank you, I will try that tomorrow!Caseate
Why do you have lean() in it the distinct will only return the ids?Unconnected
@ElishaSterngold I agree, it's certainly redundant - thanks for noticing, I updated my answer to reflect that.Turncoat
K
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.

Karinkarina answered 4/5 at 7:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.