问题描述:

Mongo DB - Aggregation of data (in MongoDB 2.1.0 - Unstable release):

db.test.save({serverName:'abc123', info:[12,43,23,10]});

db.test.save({serverName:'abc123', info:[12,22,19,11]});

db.test.aggregate({$group:{_id:"$serverName", infoTotal:{ $sum : "$info"}}});

Response: "errmsg" : "exception: the _id field for a group must not be undefined",

Not sure what I am doing wrong as the example in: http://www.mongodb.org/display/DOCS/Aggregation+Framework+-+%24group

shows how aggregation is performed.

Would appreciate some assistance. Thanks.

网友答案:

There are two issues.

1.) You have some docs which don't have a serverName in your collection. You can find them doing a find({serverName:null})

2.) You need to $unwind the array first

Here is a working sample:

> db.agg1.find()
{ "_id" : 1, "serverName" : "abc123", "info" : [ 12, 43, 23, 10 ] }
{ "_id" : 2, "serverName" : "abc124", "info" : [ 12, 22, 19, 11 ] }
{ "_id" : 3, "serverName" : "abc124", "info" : [ 1, 25, 2, 11 ] }

> db.agg1.aggregate({$unwind: "$info"},{$group:{_id:"$serverName", infoTotal:{ $sum : "$info"}}});
{
        "result" : [
                {
                        "_id" : "abc123",
                        "infoTotal" : 88
                },
                {
                        "_id" : "abc124",
                        "infoTotal" : 103
                }
        ],
        "ok" : 1
}
相关阅读:
Top