2016-10-27 28 views
0

我有一個名爲「products」的集合,其中包含「bids」對象的數組。

我想找出每個產品的最高出價,爲此我在$ max與$ bids.bidamount字段上彙總產品。然而,這隻能給我最大的出價金額。如何投影最大聚合的所有出價字段。

這裏是一個示例文件

{ 
"_id" : ObjectId("58109a5138fe12215cfdc064"), 
"product_id" : 2, 
"item_name" : "Auction Item1", 
"item_description" : "Test", 
"seller_name" : "[email protected]", 
"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" : "[email protected]", 
     "bid_amount" : 300, 
     "bit_time" : "2016:10:26 22:36:29" 
    }, 
    { 
     "bid_id" : 2, 
     "bidder" : "[email protected]", 
     "bid_amount" : 100, 
     "bit_time" : "2016:10:26 22:37:29" 
    } 
], 
"orders" : [ 
    { 
     "buyer" : "[email protected]", 
     "quantity" : "2" 
    }, 
    { 
     "buyer" : "[email protected]", 
     "quantity" : "3" 
    } 
] 

}

這裏是我的蒙戈查詢:

db.products.aggregate([ 
    { 
    $project: { 

     bidMax: { $max: "$bids.bid_amount"} 
     } 
    } 
    ]) 

其給出以下結果:

{ 
    "_id" : ObjectId("58109a5138fe12215cfdc064"), 
    "bidMax" : 300 
} 
+0

你嘗試加入投標領域該項目 ? – Veeram

回答

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」:物件( 「5811b667c50fb1ec88227860」), 「求和」:600,DOC:{文檔....}}

+0

這似乎是項目的最高報價非常久遠的原始PRODUCT_ID。 你能解釋一下管道命令的工作嗎?另外,如果我需要投影的不僅僅是id,我應該在哪裏放置額外的字段名稱。 – apps92

1

這應該做它:

db.products.aggregate([{ 
    $unwind: '$bids' 
    }, { 
    $group: { 
     _id: '$products_id', 
     maxBid: { 
     $max: '$bids.bid_amount' 
     } 
    } 
    }]) 
+0

這仍然返回: { 「_id」:空, 「maxBid」:300 } – apps92

0
db.collectionName.aggregate(
    [ 
    { 
     $group: 
     { 
      _id: "$product_id", 
      maxBidAmount: { $max: "$bids.bid_amount" } 
     } 
    } 
    ] 
) 

嘿使用此查詢,您將得到的結果。

+0

這將返回所有的投標,但我想在最高出價的所有字段。 { 「_id」:2, 「maxBidAmount」: 300,] } – apps92

相關問題