gsiradze
gsiradze

Reputation: 4733

Get distinct values from collection with another field

I have this query which returns distinct test ids from my collection

Model.find().distinct('TestId', (err, data) => { console.log(data); }

[ 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 ]

These all values has TestName as well and now I want to return them as well. Something like this:

[ {TestId: 1, TestName: 'tname'}... ]

How can I do that?

Upvotes: 0

Views: 44

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

distinct doesn't support adding other fields to the output, but you can do this with a simple aggregate pipeline:

Model.aggregate([{$group: {_id: '$TestId', TestName: {$first: '$TestName'}}}])

This will group the docs by TestId and include the TestName field from the first doc in each group.

Upvotes: 1

Related Questions