簡體   English   中英

在 ZCCADCDEDB567ABAE643E15DCF0974E503Z 中,如何合並兩種不同排序的結果,並預先指定總結果數?

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

我有一個Jar集合,它的文檔包含紅色和藍色彈珠。 如果我想在擁有大量紅色彈珠的基礎上獲得前 5 Jars,我會這樣做:

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

但是,如果我想在擁有大量紅色或藍色彈珠且沒有重復的基礎上獲得前 5 個 Jars 怎么辦? 有沒有辦法以這種方式獲取兩種不同類型的結果?

舉個例子,如果我有

[{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

您可以通過使用幾個聚合階段來做到這一點,請考慮以下幾點:

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

基本上,我向每個文檔添加了一個名為maxMarbelCount的臨時字段,該字段由最大紅色/藍色值確定。 然后,您可以( desc )按此字段排序並相應地進行限制。

如果需要,您可以添加另一個projection階段以從 output 中刪除臨時字段。

這是 mongoplayground 上的一個示例: https://mongoplayground.net/p/QApaz7YKWy8

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM