繁体   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