简体   繁体   English

在 ZCCADCDEDB567ABAE643E15DCF0974E503Z 中,如何合并两种不同排序的结果,并预先指定总结果数?

[英]In Mongoose, how do you merge the results of two different sorts, with a pre-specified number of total results?

I have a Jar collection, and its documents hold red and blue marbles.我有一个Jar集合,它的文档包含红色和蓝色弹珠。 If I wanted to get the top 5 Jars on the basis of having a lot of red marbles, I would do something like this:如果我想在拥有大量红色弹珠的基础上获得前 5 Jars,我会这样做:

Jar.find({}).sort({red: "desc"}).limit(5).exec((err, results) => { ... });

But what if I wanted to get the top 5 Jars on the basis of having a lot of red OR blue marbles, without duplicates?但是,如果我想在拥有大量红色或蓝色弹珠且没有重复的基础上获得前 5 个 Jars 怎么办? Is there a way to take the results of two different sorts in this fashion?有没有办法以这种方式获取两种不同类型的结果?

So for an example, if I have举个例子,如果我有

[{red: 20, blue: 10}, {red: 10, blue: 3}, {red: 5, blue: 22}, {red: 10, blue: 10}] , the top 3 (in descending order) will be [{red: 20, blue: 10}, {red: 10, blue: 3}, {red: 5, blue: 22}, {red: 10, blue: 10}]前3名(降序排列)将会

[{red: 5, blue: 22},  // 22 from blue is largest
{red: 20, blue: 10},  // 20 from red is 2nd largest
{red: 10, blue: 10}]  // 10 from red (or 10 from blue) is 3rd largest

You can do this by using a few aggregation stages, consider the following:您可以通过使用几个聚合阶段来做到这一点,请考虑以下几点:

db.collection.aggregate([
  {
    "$addFields": {
      maxMarbleCount: {
        $max: [
          "$red",
          "$blue"
        ]
      }
    }
  },
  {
    "$sort": {
      maxMarbleCount: -1
    }
  },
  {
    "$limit": 3
  }
])

Basically I add a temporary field called maxMarbelCount to each document, which is determined by the max red/blue value.基本上,我向每个文档添加了一个名为maxMarbelCount的临时字段,该字段由最大红色/蓝色值确定。 You can then ( desc )-sort by this field and limit accordingly.然后,您可以( desc )按此字段排序并相应地进行限制。

If needed, you can add another projection stage to remove the temporary field from the output.如果需要,您可以添加另一个projection阶段以从 output 中删除临时字段。

Here's an example on mongoplayground: https://mongoplayground.net/p/QApaz7YKWy8这是 mongoplayground 上的一个示例: https://mongoplayground.net/p/QApaz7YKWy8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM