Search code examples
node.jsmongodbmongoose

Mongoose - Get list of _ids instead of array of objects with _id


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.


Solution

  • 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.