2

I have a simple question on sorting results from the distinct command in mongodb.

I'm using Monk in my NodeJS app to get categories from my simple DB:

db.getCollection('citazioni').distinct('category')

But how can I apply a sorting function like I successfully do when I find documents with:

collection.find({}, {sort: {'_id': -1}} ??

Thank you!

daliz
  • 840
  • 2
  • 12
  • 25
  • 2
    possible duplicate of [get Distinct Values with Sorted Data](http://stackoverflow.com/questions/4759437/get-distinct-values-with-sorted-data) – Ely Jun 29 '15 at 18:38

2 Answers2

3

Monk has support for the underlying node.js native driver distinct() method and its signature is

Collection.prototype.distinct = function (field, query, fn) { ... }

As you can see from that commit that it implements the distinct method of the node native driver collection type via the .col accessor on the selected collection object:

this.col.distinct(field, query, promise.fulfill);

Thus you can implement it together with the native JavaScript sort() method as follows :

// Perform a distinct query against the category field
db.getCollection('citazioni').distinct('category', function(err, categories) {
    console.log(categories.sort());
}
chridam
  • 100,957
  • 23
  • 236
  • 235
1

Concatenate it:

db.getCollection('citazioni').distinct('category').sort({'_id': -1})

In a Node app with Mongoose:

collection.distinct('citazioni').sort({'_id': -1}).exec(function(e2, categories) { 
    ... etc ... 
}
michelem
  • 14,430
  • 5
  • 50
  • 66
  • What I'm getting is:TypeError: db.getCollection("citazioni").distinct("category").sort({_id:-1}) is not a function – daliz Jun 29 '15 at 19:05
  • What I pasted is the only code I'm running in my MongoDB shell. In Node.js (Express) I'm calling: "collection.distinct('category', function(e2, categories) { ... etc ... }" but I still don't know how to sort there. – daliz Jun 29 '15 at 19:08
  • 1
    Dear Michele, I really appreciate the time you spent looking into my issue, but I'm accepting the answer from chridam since it solves completely my problem. Thanks! – daliz Jun 29 '15 at 19:25