Trindaz
Trindaz

Reputation: 17849

How to sort this array of results?

Here is my query that attempts to sort an array of MongoDB documents based on a derived field called expiresAt. expiresAt is a Date object that represents the date string stored in doc.expirationDate.

It fails with an error TypeError: ... .sort({}) is not a function (shell):5

db.tokens.find().map(function(doc) {
    var expiryDate = new Date(doc.credentialsMap.linkedin.expirationDate);
    doc.expiresAt = expiryDate;
    return doc;
    }).sort({'expiresAt': -1});

What am I doing wrong? It's unclear to me exactly what return type map provides. If it's a cursor then why isn't sort supported? It's clearly available in the docs.

Upvotes: 0

Views: 62

Answers (1)

Roi Tal
Roi Tal

Reputation: 1000

cursor.map() returns a Java script array.

The way you're calling sort() assumes that the return value is a MongoDB cursor, that's why it fails.

You'd have to use the regular Array.sort syntax. For example, to have your map results sorted in descending order, use the following:

db.tokens.find().map(function(doc) {
var expiryDate = new Date(doc.credentialsMap.linkedin.expirationDate);
doc.expiresAt = expiryDate;
return doc;
}).sort(function(a,b) { return b.expiresAt - a.expiresAt});

Upvotes: 1

Related Questions