tags:

views:

55

answers:

2

Hi, I know how to sort queries in MongoDB by multiple fields, e.g., db.coll.find().sort({a:1,b:-1}).

Can I sort with a user-defined function; e.g., supposing a and b are integers, by the difference between a and b (a-b)?

Thanks!

+1  A: 

Why don't create the field with this operation and sort on it ?

shingara
I still need access to a and b individually. So I'd have to create a third field.That would work for my application, but as a general principle would be really bad policy. Supposing I had several integer fields, there would be a combinatorial explosion of derived attributes (a-b), (a-c), (a-d)... Even with just one field like this, it's really wasteful of space especially for a large collection.I'm upvoting and if no one else answers accepting, but there has to be a better way. In SQL this is as easy as `SELECT * FROM coll ORDER BY (a-b)` .
gilesc
+1  A: 

I don't think this is possible directly; the sort documentation certainly doesn't mention any way to provide a custom compare function.

You're probably best off doing the sort in the client, but if you're really determined to do it on the server you might be able to use db.eval() to arrange to run the sort on the server (if your client supports it).

Server-side sort:

db.eval(function() { 
  return db.scratch.find().toArray().sort(function(doc1, doc2) { 
    return doc1.a - doc2.a 
  }) 
});

Versus the equivalent client-side sort:

db.scratch.find().toArray().sort(function(doc1, doc2) { 
  return doc1.a - doc2.b 
});
mjs
Yup. After further digging I found that there's been an RFE filed to allow for convenience functions to do exactly this. I definitely don't like the looks of that `toArray()` for my ~10m documents, but that's apparently the state of affairs.
gilesc