Steve
Steve

Reputation: 923

mongodb ~ sorted distinct list / does distinct have sort()?

This doesn't, nor 100 variations, work.

db.getCollection('countryCodesAndSubCodes')
 .distinct( 'Cn', {enabled: true} )
 .sort( { Cn: 1 } );

Type error ({ Cn: 1 }) is not a function

but this does:

db.getCollection('countryCodesAndSubCodes').distinct( 'Cn', {enabled: true} );

and this too:

db.getCollection('countryCodesAndSubCodes').find({}).sort( { Cn: 1 } );

So how do you sort a distinct?

Upvotes: 0

Views: 3339

Answers (1)

Ori Dar
Ori Dar

Reputation: 19000

db.getCollection('countryCodesAndSubCodes').distinct( 'Cn', {enabled: true} ) returns a plain old javascript array (assuming a String array, but it doesn't really matter).

To sort it just call sort()

Or more specifically:

db.getCollection('countryCodesAndSubCodes').distinct( 'Cn', {enabled: true} ).sort()

Whereas db.getCollection('countryCodesAndSubCodes').find({}).sort( { Cn: 1 } ); does a cursor sort (as opposed to the array sort).

For a cursor sort you need a sort key and direction { Cn: 1 }

Upvotes: 2

Related Questions