Shimon Wiener Shimon Wiener - 3 months ago 39
Bash Question

MongoDB Aggregate framework Error

i have a collection with this structure:

{ "_id" : "01002", "city" : "CUSHMAN", "loc" : [ -72.51564999999999, 42.377017 ], "pop" : 36963, "state" : "MA" }


i want to use Aggregate framework to perform this query:

db.US.aggregate([{$group:{_id:{"state":"$state"}}, sum:{$sum:"$pop"}}])


I"m getting this error:
"Command 'aggregate' failed: exception: A pipeline stage specification object must contain exactly one field. (response: { "errmsg" : "exception: A pipeline stage specification object must contain exactly one field.", "code" : 16435, "ok" : 0.0 })"

way i get this error,it looks like a very simple one
can anybody help
Thanks

Answer

Yep your brackets were a little out of whack.

db.US.aggregate([{$group:{_id:{"state":"$state"}}, sum:{$sum:"$pop"}}])

change to:

db.US.aggregate([{$group:{_id:{"state":"$state"}, sum:{$sum:"$pop"}}}])

Edit: actually this is better:

db.US.aggregate([
    {$group:{_id:"$state", sum:{$sum:"$pop"}}}
])

since it results in a flat document instead of an array of ids:

{ "_id" : "MA", "sum" : 36963 }