Reputation: 183
I have this query stored in a variable as follows
var recent_Polls = db.Trump_Vs_Biden_V1.aggregate(
[
{ $match : {"State":state_Val}},
{$sort:{"Date":-1}},
{$limit: 5 }
]
)
and it returns these 5 documents
As u can see in each document there is
"Biden" : 59, "Trump" : 32
I wish to get all of the Biden values into one array and all the trump values into a seperate array so i can perform mathematical operations on them.
So for example this is the desired output i would like for all the trump values..
[
36,
32,
32,
31,
36
]
and vice versa for biden...
in order to do this i attempted using the .map function.
var trump_Nums = recent_Polls.map(function(e2){return e2.Trump})
And this worked but when i tried to perform the exact same operation on the biden values
recent_Polls.map(function(e2){return e2.Biden})
i got an empty array in return..
I was wondering if anybody could think of a fix to this were i could retrieve both the trump and biden values all at once into 2 seperate arrays. That is maybe more efficient..
Upvotes: 0
Views: 25
Reputation: 28326
To get this on the client side, you might try forEach:
var trump_Nums = [];
var biden_Nums = [];
recent_Polls.forEach(function(e2){
trump_Nums.push(e2.Trump);
biden_Nums.push(e2.Biden)
});
To get this from the server, add a $group stage to the aggregation:
{$group: {
_id:null,
Biden:{$push: "$Biden"},
Trump:{$push: "$Trump"}
}}
If you need the full documents at the same time as the numbers, add a $facet stage to your original aggregation:
{$facet: {
documents:[{$match:{}}],
numbers: [{$group: {
_id:null,
Biden:{$push: "$Biden"},
Trump:{$push: "$Trump"}
}}]
}}
Upvotes: 1