mongodb将计算结果进行排序

将record集合中status为1的数据的点赞量、分享量、浏览量进行计算之后进行排序处理。
mongodb代码

db.record.aggregate(
    [{
        "$match": {
            "status": 1
        }
    }, {
        "$project": {
            "authorId": 1,
            "position": 1,
            "statisticsInfo":1,
            "total": {
                "$divide": [{
                    "$add": ["$statisticsInfo.likeNum", "$statisticsInfo.shareNum"]
                }, {
                    "$cond": {
                        "if": {
                            "$eq": ["$statisticsInfo.browseNum", 0]
                        },
                        "then": 1,
                        "else": "$statisticsInfo.browseNum"
                    }
                }]
            }
        }
    }, {
        "$sort": {
            "total": - 1,
			"time": - 1	
        }
    }]
)

java代码

Criteria criteria = Criteria.where("status").is(IsStatusEnum.YES.getStatus());
Aggregation aggregation = Aggregation.newAggregation(
                match(criteria),
                //Aggregation.geoNear(NearQuery.near(new Point(lon, lat)),"positionInfo.position"),
                project("authorId",
                        "statisticsInfo",
                        "positionInfo")
                        //日期按照天(年月日)降序
                        .andExpression(
                                "{$dateToString:{format:'%Y-%m-%d',date:{$toDate:'$publishTime'}}}"
                        ).as("time")
                        //统计算法
                        .andExpression("{'$divide': {{" +
                                "                    '$add': {'$statisticsInfo.likeNum', '$statisticsInfo.shareNum'}" +
                                "                }, {" +
                                "                    '$cond': {" +
                                "                        'if': {" +
                                "                            '$eq': {'$statisticsInfo.browseNum', 0}" +
                                "                        }," +
                                "                        'then': 1," +
                                "                        'else': '$statisticsInfo.browseNum'" +
                                "                    }" +
                                "                }}" +
                                "}"
                        ).as("total"),
                sort(Sort.Direction.DESC, "time","total"),
                // 默认查询10条记录
                skip(pageNo  > 1 ? (pageNo - 1) * 10 : 0L),
                limit(10)
        );

版权声明:本文为weixin_39048904原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。