Mongo复杂排序? [英] Mongo complex sorting?

查看:31
本文介绍了Mongo复杂排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在 MongoDB 中按多个字段对查询进行排序,例如 db.coll.find().sort({a:1,b:-1}).

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

我可以用用户定义的函数排序吗?例如,假设 a 和 b 是整数,通过 a 和 b 之间的差异 (a-b)?

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)?

谢谢!

推荐答案

更新: 此答案似乎已过时;通过使用 似乎可以或多或少地实现自定义排序$project 聚合管道的功能 在排序之前转换输入文档.另请参阅@Ari 的回答.

UPDATE: This answer appears to be out of date; it seems that custom sorting can be more or less achieved by using the $project function of the aggregation pipeline to transform the input documents prior to sorting. See also @Ari's answer.

我不认为这是直接可能的;排序文档当然没有提到任何提供自定义比较函数.

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

您可能最好在客户端进行排序,但如果您真的决定在服务器上进行排序,您或许可以使用 db.eval() 来安排在服务器上运行排序(如果您的客户端支持).

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).

服务端排序:

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 
});

请注意,也可以通过 聚合管道 进行排序,并且通过 $orderby 运算符(即在除了 .sort()) 但是这些方法都不能让您提供自定义排序功能.

Note that it's also possible to sort via an aggregation pipeline and by the $orderby operator (i.e. in addition to .sort()) however neither of these ways lets you provide a custom sort function either.

这篇关于Mongo复杂排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆