2015-09-21 25 views
0

MongoDB的總和名單,我有以下數據:與條件

{ "_id" : ObjectId("55fbffbdebdbc43337b08946"), "date" : 1442578343617, 
    "body" : { "entries" : [ 
     { "url" : "google.com/randomString", "time" : 143.832}, 
     { "url" : "youtube.com/randomString", "time" : 170.128}, 
     { "url" : "google.com/randomString", "time" : 125.428} 
    ] } } 

我要總結的是需要加載google.com網頁的時間。

我所試圖做的是:

db.har.aggregate([ 
     {$match: {date: 1442578343617, "body.entries.url": /google/}}, 
     { $unwind : "$body.log.entries"}, 
     { $group : {"_id" : 123,"total" : {$sum:"$body.entries.time"}}} 
    ]) 

但結果我得到的是總和:{ "_id" : 123, "total" : 439.388 }

如何通過body.entries.url過濾器?

非常感謝您的寶貴時間

+1

你忘了另一個**'$ match'後**管道一步**'$ unwind' **階段將進一步將文檔過濾到**'$ group' **管道。 – chridam

回答

0

這裏你平倉錯陣列body.log.entries

您需要的首場比賽日期戳過濾掉的文件,然後使用$放鬆,再搭配body.entries.url,如:

db.collection.aggregate([{ 
    $match: { 
    date: 1442578343617 
    } 
}, { 
    "$unwind": "$body.entries" 
}, { 
    $match: { 
    "body.entries.url": /google/ 
    } 
}, { 
    $group: { 
    "_id": null, //you can use any other param here 
    "total": { 
     $sum: "$body.entries.time" 
    } 
    } 
}]) 
+0

非常感謝,它解決了我的問題 – HectorAnadon

0

過濾通過URL展開前,使所有包含一個谷歌的網址文件。但它也會保留包含谷歌的文檔的其他網址(在這種情況下:youtube)。所以當你放鬆時,你仍然會擁有那些youtube urls而不會過濾它們。

所以才:

db.har.aggregate([ 
    {$match: {date: 1442578343617}, 
    {$unwind : "$body.log.entries"}, 
    {$match: {"body.entries.url": /google/}, 
    {$group: {"_id" : 123,"total" : {$sum:"$body.entries.time"}}} 
]) 
+0

非常感謝,這也解決了我的問題 – HectorAnadon