[英]Find all possible mongodb combinations of two fields
I have in database the next array of objects我在数据库中有下一个对象数组
[
{
price: "1"
type: "buy",
},
{
price: "2"
type: "buy",
},
{
price: "3"
type: "sell"
},
{
price: "4"
type: "sell"
}
]
How can I make an aggregation to get an array of arrays with all possible combinations (price could be random number)如何进行聚合以获取具有所有可能组合的数组数组(价格可能是随机数)
hide items with the highest buy price隐藏购买价格最高的物品
and sort them, so the items with the largest price difference are at the top并对它们进行排序,因此价格差异最大的商品位于顶部
[
[
{
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"
},
],
]
Query询问
*i am not sure it does all you need, because i didn't understand the part hide items with the highest buy price
the highest buy price is "2" and in your results you have this items *我不确定它是否满足您的所有需求,因为我不明白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.