mongodb Mongo复杂排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3212919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 11:45:43  来源:igfitidea点击:

Mongo complex sorting?

mongodb

提问by gilesc

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

我知道如何按多个字段对 MongoDB 中的查询进行排序,例如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)?

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

Thanks!

谢谢!

采纳答案by mjs

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

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



I don't think this is possible directly; the sort documentationcertainly 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).

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

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

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

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

回答by Ari

Ran into this and this is what I came up with:

遇到了这个,这就是我想出的:

db.collection.aggregate([
  { 
    $project: {
      difference: { $subtract: ["$a", "$b"] }
      // Add other keys in here as necessary
    }
  },  
  { 
    $sort: { difference: -1 } 
  }
])

回答by shingara

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

为什么不使用此操作创建字段并对其进行排序?