查找两个字段的所有可能 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"
      },
  ],
]

查询

  • self-lookup 如果 id 不同则匹配(避免成对出现相同的项目)
  • 将父项添加到连接结果的映射(该对将始终以价格最高的那个作为第一个成员(稍后需要))
  • 展开对
  • 分组对以删除重复项(每对将出现 2 次,但它是从地图中排序的,因此我们可以按它分组)
  • 查找差价,降序排列,取消设置字段

*我不确定它是否满足您的所有需求,因为我不理解 hide items with the highest buy price 最高购买价格是“2”的部分,在您的结果中您有这些商品

Playmongo

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"]}])