db.collection.aggregate([
{$sort:{score:-1}}, //按照分数排序
{$group:{_id:null,all:{$push:"$openid"}}}, // 将所有排序结果push到all数组中,方便下面使用$indexOfArray
{$project:{_id:0,total:{$size:"$all"},index:{ $indexOfArray:[ "$all",openid] }}} // 这里的openid为要查找名次的openid
])
// 返回结果类似下面这样: total 总人数,index 为名次
{ "total" : 3, "index" : 1 }
db.getCollection('sheets').aggregate([
{
$match: {'paper._id': ObjectId('5def7cb7305f898f600c7496')}
},
{'$sort': {'right': -1, 'times': 1}},
{'$project': {'user_id': '$author._id'}},
{'$group': {'_id': null, 'items': {'$push': '$$ROOT'}}},
{'$unwind': {'path': '$items', 'includeArrayIndex': 'rank'}},
])
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。