和SQL的对应关系:
WHERE $match (page 281)
GROUP BY $group (page 278)
HAVING $match (page 281)
SELECT $project (page 285)
ORDER BY $sort (page 287)
LIMIT $limit (page 280)
SUM() $sum
COUNT() $sum
join No direct corresponding operator; however, the $unwind (page 290) operator allows for
somewhat similar functionality, but with fields embedded within the document.
// create our pipeline operations, first with the $matchDBObjectmatch=newBasicDBObject("$match",newBasicDBObject("type","airfare"));// build the $projection operationDBObjectfields=newBasicDBObject("department",1);fields.put("amount",1);fields.put("_id",0);DBObjectproject=newBasicDBObject("$project",fields);// Now the $group operationDBObjectgroupFields=newBasicDBObject("_id","$department");groupFields.put("average",newBasicDBObject("$avg","$amount"));DBObjectgroup=newBasicDBObject("$group",groupFields);// run aggregationAggregationOutputoutput=collection.aggregate(match,project,group);
spring data mongodb,@since 1.3,注意升级
官方例子是对城市人口做统计,group两次(对第一次group的结果再group)
好处在于对结果进行了封装,返回List,注意ZipInfoStats嵌套City,使用nested和bind:
db.zipcodes.aggregate({$group:{_id:{state:"$state",city:"$city"},pop:{$sum:"$pop"}}},{$sort:{pop:1}},{$group:{_id:"$_id.state",biggestCity:{$last:"$_id.city"},biggestPop:{$last:"$pop"},smallestCity:{$first:"$_id.city"},smallestPop:{$first:"$pop"}}},// the following $project is optional, and// modifies the output format.{$project:{_id:0,state:"$_id",biggestCity:{name:"$biggestCity",pop:"$biggestPop"},smallestCity:{name:"$smallestCity",pop:"$smallestPop"}}})