Reputation: 840
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!
Upvotes: 2
Views: 2960
Reputation: 103365
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());
}
Upvotes: 3
Reputation: 14590
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 ...
}
Upvotes: 1