MongoDB 聚合查询 名次 问题

2019-11-07  本文已影响0人  野十六
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'}},
])
上一篇 下一篇

猜你喜欢

热点阅读