我们正在使用mongoose
我们有这个集合
{
"_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][0@0][0].dav",
"recordingDuration" : 11.042,
"recordingLocation" : "/opt/safecamz/recording/55950adaa24f46d255acfe90/559514d3f20fb7e959a5b078/video/23.26.09-23.27.33[M][0@0][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][0@0][0].mp4",
"recordingName" : "23.26.09-23.27.33[M][0@0][0].mp4",
"__v" : 0
}
现在我们要通过 userId 添加 recordingSize 例如,如果有10,000个记录,那么recordingSize的总和,其中userId = ObjectId(" 55950adaa24f46d255acfe90")
我们尝试使用$sum
,但我们无法获得正确的输出
答案 0 :(得分: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)。