欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MongoDB 分组查询(Group)

程序员文章站 2024-03-11 10:53:13
...

MongoDB 分组查询(Group)

集合:collectTest
{
    "_id" : NumberLong("908531627875254272"),
    "_class" : "com.XXXX",
    "tripId" : NumberLong("908531628206604288"),
    "userId" : NumberLong("888236517070209024"),
    "payAmount" : "77.80",
    "orderPrice" : "77.80",
    "couponValue" : "0",
    "insurancePrice" : "0",
    "payType" : "BALANCE",
    "orderStatus" : "CANCELED",
    "payStatus" : "NOT_NEED_PAY",
    "paidTime" : ISODate("2017-09-15T12:29:26.035+08:00"),
    "orderCode" : "cra20170915000001",
    "createTime" : ISODate("2017-09-15T11:23:14.522+08:00")
}

分组查询如下:

类似与 sql中的 select userId,count(*) from tableName group by userId;

db.collectTest.aggregate([
    { 
          $match: {
            "userId": NumberLong("888236517070209024"),
            "orderStatus": "CANCELED"
         }
    },
    {
        $group: {
            _id: "$userId",
            count: {
                $sum: 1
            }
        }
    }
]);

一些聚合的表达式请参考 这里写链接内容


在 java 中使用MongoTemplate 的调用方式如下:

 public void groupTest(){
        List<DBObject> list = Lists.newArrayList(new BasicDBObject("$match", new BasicDBObject("orderStatus", "CANCELED")
                .append("userId",888236517070209024L)

        ),new BasicDBObject("$group",new BasicDBObject("_id","$userId").append("total", new BasicDBObject("$sum",1)))

        );
        Cursor cursor = mongoTemplate.getCollection("collectTest").aggregate(list, AggregationOptions.builder().build());

        while (cursor.hasNext()){
            cursor.next();
        }
    }
相关标签: Mongodb Group