db.item.aggregate([
{
$group: {
_id: "$name",
count: {
"$sum": 1
}
}
},
{
$project: {
_id: 0,
name: "$_id",
count: 1
}
}
]).pretty();
一个java实现将是这样的
final MongoClient mongoClient = new MongoClient();
final DB db = mongoClient.getDB("DB_NAME");
final DBCollection collection = db.getCollection("item");
final DBObject groupIdFields = new BasicDBObject("_id", "$name");
groupIdFields.put("count", new BasicDBObject("$sum", 1));
final DBObject group = new BasicDBObject("$group", groupIdFields);
final DBObject projectFields = new BasicDBObject("_id", 0);
projectFields.put("name", "$_id");
projectFields.put("count", 1);
final DBObject project = new BasicDBObject("$project", projectFields);
final AggregationOutput aggregate = collection.aggregate(group, project);