2015-07-03 78 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