Reputation: 2435
Before I begin, I want to state that no other answers regarding similar questions applied to this one. First consider the following JSON code
"_id": "1412302013-01-20,11:32:22"
"display": [
{
"Name": "LOG-11-05-SH-O1.mp4",
"Type": "Startup",
"Count": 2,
"Detail": [
{
"Start": "2013-01-20,11:32:22",
"End": "2013-01-20,11:32:30"
},
{
"Start": "2013-01-20,11:32:22",
"End": "2013-01-20,11:32:30"
}
]
},
{
"Name": "PUR-12-47-SH-X3.mp4",
"Type": "Movie",
"Count": "2",
"Detail": [
{
"Start": "2013-01-20,11:32:22",
"End": "2013-01-20,11:32:30"
},
{
"Start": "2013-01-20,11:32:22",
"End": "2013-01-20,11:32:30"
}
]
},
The ID is basically a combination of a license plate number concatted with a time stamp.
What I am trying to do is aggregate the sum for "Count"
, where the "Name": "LOG-11-05-SH-O1.mp4"
.
I could not even get simple sums to be aggregated, so trying to aggregate this sum has been impossible. When running my script in NodeJS, I either get undefined
or [object Object]
.
I have no clue what is going wrong as I've been following various online examples.
After trying to use parvin's answer below, I am still getting undefined:
collection.aggregate([
{$match : {"display.Name" : "LOG-11-05-SH-O1.mp4"}},
{$unwind : "$display"},
{$group : {_id : "$_id",
name : {$first : "$display.Name"},
total : {$sum : "$display.Count"}
}
}], function(err, result) {
console.log("Aggregation: " + result.total);
});
I've been trying to format the code like these docs.
Upvotes: 0
Views: 7226
Reputation: 311835
The aggregate
callback's result
parameter is an array, not a single value. You can see this if you just dump out result
:
console.log(result);
So to access total
of the first doc in the array:
console.log(result[0].total);
But that's going to be 0 because Count
in your doc is a string, not a number. You can't $sum
strings.
Because you also only want the total
for only the "Name": "LOG-11-05-SH-O1.mp4"
elements, you need to add another filter after your $unwind
:
collection.aggregate([
{$match : {"display.Name" : "LOG-11-05-SH-O1.mp4"}},
{$unwind : "$display"},
{$match : {"display.Name" : "LOG-11-05-SH-O1.mp4"}},
{$group : {_id : "$_id",
name : {$first : "$display.Name"},
total : {$sum : "$display.Count"}
}
}], function(err, result) {
console.log(result);
});
Upvotes: 3
Reputation: 26012
You can use the following query to find the total count for the Name = "LOG-11-05-SH-O1.mp4"
. This is the javascript example, you have to convert it to node.js
db.collection.aggregate(
{$match : {"display.Name" : "LOG-11-05-SH-O1.mp4"}},
{$unwind : "$display"},
{$group : {_id : "$_id",
name : {$first : "$display.Name"},
total : {$sum : "$display.Count"}
}}
)
Upvotes: 1