Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialHenry Lin
11,636 PointsHow to access a result field that stored in a variable?
I have a query like this:
var a = db.reviews.aggregate([
{
$unwind:"$Reviews"
},
{
$match: {"HotelInfo.Name": "Desert Rose Resort"}
},
{
$group:
{
_id:"$HotelInfo.Name",
avg: {$avg: "$Reviews.Ratings.Overall"}
}
}
])
And it returned me:
{
"result": [
{
"_id": "Desert Rose Resort",
"avg": 4.522628226617499
}
],
"ok": 1
}
I want to access the "avg" field in Var a.. I am pretty sure it should looks like something like a[0].avg this.. but It did not work.. Anyone knows this?
1 Answer
Greg Kaleka
39,021 PointsHi Henry,
You're very close! You just need to use the result
key before you subscript into its value, a list (which you're doing correctly).
So instead of a[0].avg
, you need a.result[0].avg
. Let me know if you don't understand why!
Cheers
-Greg