我在聚合方面遇到了麻烦。我有这些领域的收藏“站”:
stationName: string,
systemName: string,
commodities:[{
name: string,
buyPrice: number,
sellPrice: number,
stock: number,
demand: number
}]
我需要查询特定商品的最高和最低价格。例如:我有商品“水”,需要在所有站点条目中获得最高的销售价格。
提前致谢
答案 0 :(得分:0)
您可以尝试使用 aggregate
/$max
进行 $min
查询,
db.collection.aggregate([
{
$project: {
stationName: true,
systemName: true,
maxBuyPrice: {
$max: "$commodities.buyPrice"
},
maxSellPrice: {
$max: "$commodities.sellPrice"
},
}
}
])
对于最低价格,您可以在查询中将 $max
替换为 $min
,或者如果您需要,可以同时包含两者
答案 1 :(得分:-1)
db.stations.aggregate([
{ $unwind: "$commodities"},
{ $match: { "commodities.name":"clothing" }}, //clothing as example
{ $sort: { "commodities.buyPrice":-1 }},
{ $limit: 10}
])
这对我有用。