[英]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"
},
],
]
询问
*我不确定它是否满足您的所有需求,因为我不明白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.