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

问题描述

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

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复杂的分类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 03:47