簡體   English   中英

查找兩個字段的所有可能的 mongodb 組合

[英]Find all possible mongodb combinations of two fields

我在數據庫中有下一個對象數組

[
  {
     price: "1"
     type: "buy",
  },
  {
     price: "2"
     type: "buy",
  },
  {
     price: "3"
     type: "sell"
  },
  {
     price: "4"
     type: "sell"
  }
]

如何進行聚合以獲取具有所有可能組合的數組數組(價格可能是隨機數)

隱藏購買價格最高的物品

並對它們進行排序,因此價格差異最大的商品位於頂部

[
  [
      {
         price: "1"
         type: "buy",
      },
      {
         price: "4"
         type: "sell"
      }
  ],
  [
      {
         price: "1"
         type: "buy",
      },
      {
         price: "3"
         type: "sell"
      },
  ],
  [
      {
         price: "2"
         type: "buy",
      },
      {
         price: "4"
         type: "sell"
      }
  ],
  [
      {
         price: "2"
         type: "buy",
      },
      {
         price: "3"
         type: "sell"
      },
  ],
]

詢問

  • 如果 ID 不同,則自行查找和匹配(避免配對中的相同項目)
  • 映射以將父項添加到聯接結果(該對將始終將價格最高的那個作為第一個成員(稍后需要))
  • 展開對
  • 分組對以刪除重復項(每對將出現 2 次,但它是從地圖中排序的,因此我們可以按它分組)
  • 查找價格差異,按降序排序,取消設置字段

*我不確定它是否滿足您的所有需求,因為我不明白hide items with the highest buy price的部分最高購買價格是“2”並且在您的結果中您有這些物品

玩蒙哥

coll.aggregate(
[{"$lookup": 
   {"from": "coll",
    "pipeline": 
     [{"$match": {"$expr": {"$ne": ["$$id", "$_id"]}}},
       {"$project": {"_id": 0, "price": 1, "type": 1}}],
    "as": "pairs",
    "let": {"id": "$_id"}}},
 {"$project": 
   {"_id": 0,
    "pairs": 
     {"$map": 
       {"input": "$pairs",
        "in": 
         {"$cond": 
           [{"$gt": ["$$this.price", "$price"]},
             [{"price": "$price", "type": "$type"}, "$$this"],
             ["$$this", {"price": "$price", "type": "$type"}]]}}}}},
 {"$unwind": "$pairs"}, {"$group": {"_id": "$pairs"}},
 {"$project": {"_id": 0, "pair": "$_id"}},
 {"$set": 
   {"priceDifference": 
     {"$abs": 
       {"$subtract": 
         [{"$toDouble": 
             {"$getField": 
               {"field": "price", "input": {"$arrayElemAt": ["$pairs", 0]}}}},
           {"$toDouble": 
             {"$getField": 
               {"field": "price",
                "input": {"$arrayElemAt": ["$pairs", 1]}}}}]}}}},
 {"$sort": {"priceDifference": -1}},
 {"$unset": ["priceDifference"]}])

暫無
暫無

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

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