我在資料庫中有下一個物件陣列
[
{
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"
},
],
]
uj5u.com熱心網友回復:
詢問
- 如果 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"]}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/483614.html
標籤:javascript 数组 mongodb 猫鼬 mongodb查询
上一篇:在nodejs中,如何在嵌入的mongodb檔案之間遍歷以獲取其鍵的值
下一篇:貓鼬在檔案物件中查找
