美文网首页
MongoDB 聚合查询 名次 问题

MongoDB 聚合查询 名次 问题

作者: 野十六 | 来源:发表于2019-11-07 15:51 被阅读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'}},
])

相关文章

网友评论

      本文标题:MongoDB 聚合查询 名次 问题

      本文链接:https://www.haomeiwen.com/subject/tisvbctx.html