【发布时间】:2017-06-26 16:27:34
【问题描述】:
我有一个这样的“订单”集合:
{ typeID: 1, buyOrder: true, price: 100 },
{ typeID: 1, buyOrder: false, price: 120 },
{ typeID: 1, buyOrder: false, price: 130 },
{ typeID: 1, buyOrder: false, price: 250 },
{ typeID: 2, buyOrder: true, price: 500 },
{ typeID: 2, buyOrder: false, price: 610 },
{ typeID: 2, buyOrder: false, price: 690 },
{ typeID: 2, buyOrder: false, price: 590 }
我想汇总这个集合并找到每个 typeid 的最佳买入/卖出价格。
结果应该是:
{ typeID: 1, bestBuy: 100, bestSell: 120 }
{ typeID: 2, bestBuy: 500, bestSell: 610 }
定义 bestBuy / bestSell
bestBuy = (buyOrder = true && max price)
bestSell = (buyOrder = false && min price)
这是我目前所拥有的,但我知道这是错误的。有任何想法吗 ?
db.orders.aggregate([
{ $sort : { typeID : 1 }},
{ $group:
{ _id: { typeID : "$typeID", buyOrder : "$buyOrder"},
price: { $max: "$price" },
}
},
{ $project:
{ _id: 0,
typeID: "$_id.typeID",
price: "$price",
buyOrder: "$_id.buyOrder",
}
}
])
感谢您的宝贵时间。
【问题讨论】:
-
你如何定义 bestBuy 和 bestSell?
-
忘了说。
bestBuy = (buyOrder = true && max price)和bestSell = (buyOrder = false && min price) -
inmongodb.net/2015/11/… 你会得到最好的聚合框架参考
标签: mongodb mongodb-query aggregation-framework