Reputation: 1605
we are using mongoose
We have this collection
{
"_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
}
Now we want to add recordingSize by userId for example if there are 10,000 recording then sum of recordingSize where userId=ObjectId("55950adaa24f46d255acfe90")
we try to use $sum
but we are unable to get correct output
Upvotes: 0
Views: 35
Reputation: 1155
You can use aggregation. Let's assume sample data derived from your sample:
> 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" }
Let's try recordingDuration
first and see the sum in totalDuration
:
> db.recordings.aggregate([{$project: {userId:1, recordingDuration:1}}, {$group: { _id: '$userId', totalDuration: { $sum: '$recordingDuration' }}}])
{ "_id" : ObjectId("55950adaa24f46d255acfe90"), "totalDuration" : 22.084 }
The problem is that recordingSize
is a String, that's why $sum
will not work:
> db.recordings.aggregate([{$project: {userId:1, recordingSize:1}}, {$group: { _id: '$userId', totalSize: { $sum: '$recordingSize' }}}])
{ "_id" : ObjectId("55950adaa24f46d255acfe90"), "totalSize" : 0 }
More details here: $sum (aggregation).
Upvotes: 1