mongoDB笔记

Posted by laosuan on December 4, 2020

$group (aggregation)

// 准备数据
db.sales.insertMany([
  { "_id" : 1, "item" : "abc", "price" : NumberDecimal("10"), "quantity" : NumberInt("2"), "date" : ISODate("2014-03-01T08:00:00Z") },
  { "_id" : 2, "item" : "jkl", "price" : NumberDecimal("20"), "quantity" : NumberInt("1"), "date" : ISODate("2014-03-01T09:00:00Z") },
  { "_id" : 3, "item" : "xyz", "price" : NumberDecimal("5"), "quantity" : NumberInt( "10"), "date" : ISODate("2014-03-15T09:00:00Z") },
  { "_id" : 4, "item" : "xyz", "price" : NumberDecimal("5"), "quantity" :  NumberInt("20") , "date" : ISODate("2014-04-04T11:21:39.736Z") },
  { "_id" : 5, "item" : "abc", "price" : NumberDecimal("10"), "quantity" : NumberInt("10") , "date" : ISODate("2014-04-04T21:23:13.331Z") },
  { "_id" : 6, "item" : "def", "price" : NumberDecimal("7.5"), "quantity": NumberInt("5" ) , "date" : ISODate("2015-06-04T05:08:13Z") },
  { "_id" : 7, "item" : "def", "price" : NumberDecimal("7.5"), "quantity": NumberInt("10") , "date" : ISODate("2015-09-10T08:43:00Z") },
  { "_id" : 8, "item" : "abc", "price" : NumberDecimal("10"), "quantity" : NumberInt("5" ) , "date" : ISODate("2016-02-06T20:20:13Z") },
])

// 按item字段统计
db.sales.aggregate( [ { $group : { _id : "$item" } } ] )
// 结果
{ "_id" : "abc" }
{ "_id" : "jkl" }
{ "_id" : "def" }
{ "_id" : "xyz" }

// 统计总价
db.sales.aggregate(
  [
    // First Stage
    {
      $group :
        {
          _id : "$item",
          totalSaleAmount: { $sum: { $multiply: [ "$price", "$quantity" ] } }
        }
     },
     // Second Stage
     {
       $match: { "totalSaleAmount": { $gte: 100 } }
     }
   ]
 )
 
 // 结果
 
{ "_id" : "abc", "totalSaleAmount" : NumberDecimal("170") }
{ "_id" : "xyz", "totalSaleAmount" : NumberDecimal("150") }
{ "_id" : "def", "totalSaleAmount" : NumberDecimal("112.5") }


// java案例
db.Answer.aggregate({
	"$match": {
		"author.loginName": "bfxujia"
	}
}, {
	"$group": {
		"_id": "$category._id",
		"count": {
			"$sum": 1
		}
	}
}, {
	"$skip": 0
}, {
	"$limit": 30
}
Criteria criteria = Criteria.where("author.loginName").is(loginName);
        Aggregation agg = newAggregation(
            match(criteria), group("$category.id").count().as("count"), skip(from), limit(size));
        // Convert the aggregation result into a List
        AggregationResults<CategoryCount> groupResults = mongoTemplate.aggregate(agg, Answer.class, CategoryCount.class);
        return groupResults.getMappedResults();
        
public class CategoryCount {
    private String _id;
    private long count;
}

// 统计数目
db.Answer.aggregate({
"$match": {
"author.type": "user" ,
"createdAt": {
        "$gt": ISODate("2020-10-11T00:53:24.706+0000")
    }
}
}, {
"$group": {
"_id": "$author.loginName",
"count": {
"$sum": 1
}
}
}, {"$sort": {"count" : -1} })

reference:

1 https://docs.mongodb.com/manual/reference/operator/aggregation/group/