我有一个名为“products”的集合,其中包含一系列“出价”对象。
我想了解每种产品的最高出价,为此我使用$ bid.bidamount字段在$ max上汇总产品。然而,这只给了我最大的出价金额。如何为最大聚合投影所有出价字段。
这是一个示例文档
{
"_id" : ObjectId("58109a5138fe12215cfdc064"),
"product_id" : 2,
"item_name" : "Auction Item1",
"item_description" : "Test",
"seller_name" : "ak@gmail.com",
"item_price" : "20",
"item_quantity" : 7,
"sale_type" : "Auction",
"posted_at" : "2016:10:26 04:58:09",
"expires_at" : "2016:10:30 04:58:09",
"bids" : [
{
"bid_id" : 1,
"bidder" : "ak@gmail.com",
"bid_amount" : 300,
"bit_time" : "2016:10:26 22:36:29"
},
{
"bid_id" : 2,
"bidder" : "ak@gmail.com",
"bid_amount" : 100,
"bit_time" : "2016:10:26 22:37:29"
}
],
"orders" : [
{
"buyer" : "ak@gmail.com",
"quantity" : "2"
},
{
"buyer" : "ak@gmail.com",
"quantity" : "3"
}
]
}
这是我的mongo查询:
db.products.aggregate([
{
$project: {
bidMax: { $max: "$bids.bid_amount"}
}
}
])
得出以下结果:
{
"_id" : ObjectId("58109a5138fe12215cfdc064"),
"bidMax" : 300
}
答案 0 :(得分:1)
这应该这样做:
db.products.aggregate([{
$unwind: '$bids'
}, {
$group: {
_id: '$products_id',
maxBid: {
$max: '$bids.bid_amount'
}
}
}])
答案 1 :(得分:1)
db.products.aggregate([{$unwind:"$bids"},{$group:{_id:"$_id", sum:{$sum:"$bids.bid_amount"}}},{$project:{doc:"$$ROOT", _id:1, sum:1}, {$sort:{"sum":-1}},{$limit:1}]),
返回类似{" _id" :ObjectId(" 5811b667c50fb1ec88227860")," sum" :600,doc:{your document ....}}
答案 2 :(得分:0)
db.collectionName.aggregate(
[
{
$group:
{
_id: "$product_id",
maxBidAmount: { $max: "$bids.bid_amount" }
}
}
]
)
嘿,请使用此查询,您将获得结果。