2015-07-03 139 views
0

我們用貓鼬總和某一特定領域的通過匹配特定領域

我們有這個集合

{ 
    "_id" : ObjectId("5596c195336cbb042728c83b"), 
    "cameraId" : ObjectId("559514d3f20fb7e959a5b078"), 
    "orignalFilePath" : "/opt/safecamz/recording/55950adaa24f46d255acfe90/559514d3f20fb7e959a5b078/1A01270PAA0012/2000-01-09/001/dav/23/23.26.09-23.27.33[M][[email protected]][0].dav", 
    "recordingDuration" : 11.042, 
    "recordingLocation" : "/opt/safecamz/recording/55950adaa24f46d255acfe90/559514d3f20fb7e959a5b078/video/23.26.09-23.27.33[M][[email protected]][0].mp4", 
    "userId" : ObjectId("55950adaa24f46d255acfe90"), 
    "created" : ISODate("2015-07-03T17:08:37.537Z"), 
    "recordingSize" : "1259.3857421875", 
    "recordingWowzaUrl" : "55950adaa24f46d255acfe90/559514d3f20fb7e959a5b078/video/23.26.09-23.27.33[M][[email protected]][0].mp4", 
    "recordingName" : "23.26.09-23.27.33[M][[email protected]][0].mp4", 
    "__v" : 0 
} 

現在,我們要添加recordingSize通過用戶id 例如,如果有10000然後記錄其中userId = ObjectId(「55950adaa24f46d255acfe90」)的記錄大小的總和

我們嘗試使用$sum但是w e無法獲得正確的輸出

回答

1

您可以使用聚合。假設從樣品來源的樣本數據:

> db.recordings.find({}, {_id: 0, userId: 1, recordingSize: 1, recordingDuration:1}) 
{ "recordingDuration" : 11.042, "userId" : ObjectId("55950adaa24f46d255acfe90"), "recordingSize" : "1259.3857421875" } 
{ "recordingDuration" : 11.042, "userId" : ObjectId("55950adaa24f46d255acfe90"), "recordingSize" : "3000.3857421875" } 

讓我們嘗試recordingDuration第一和看到totalDuration總和:

> db.recordings.aggregate([{$project: {userId:1, recordingDuration:1}}, {$group: { _id: '$userId', totalDuration: { $sum: '$recordingDuration' }}}]) 
{ "_id" : ObjectId("55950adaa24f46d255acfe90"), "totalDuration" : 22.084 } 

的問題是,recordingSize是一個字符串,這就是爲什麼$sum將無法​​正常工作:

> db.recordings.aggregate([{$project: {userId:1, recordingSize:1}}, {$group: { _id: '$userId', totalSize: { $sum: '$recordingSize' }}}]) 
{ "_id" : ObjectId("55950adaa24f46d255acfe90"), "totalSize" : 0 } 

更多細節在這裏:$sum (aggregation)

+0

Opps你是正確的,現在我把它改爲數字你可以請查詢在哪裏首先它匹配userId,然後返回記錄大小的總和,在您的查詢中發現所有,但我只想爲一個特定的用戶 – abhaygarg12493

+0

然後你只需要添加一個'$ match'像這樣:'db.recordings.aggregate([{$ match:{userId:ObjectId(「55950adaa24f46d255acfe90」)}},{$ project:{userId:1,recordingDuration:1} },{$ group:{_id:'$ userId',totalDuration:{$ sum:'$ recordingDuration'}}}])'。更多細節:http://docs.mongodb.org/manual/reference/operator/aggregation/match/ –

+0

我找到了我們使用這個查詢的解決方案: db.recordings.aggregate([{$ match:{userId:ObjectId(「 55924170480ba7ec307f6a76「)}},{$ group:{_id:'$ userId',totalSize:{$ sum:'$ recordingSize'}}}]) 感謝您的幫助 – abhaygarg12493