基于计数的Mongo排名计算

时间:2019-05-06 06:52:31

标签: mongodb mongodb-query aggregation-framework

我正在尝试基于计数的mongo排名计算,并在下面的数据库模式中提到。我没有得到预期的结果。任何人都可以解决吗?

Mongo查询:

    db.company.aggregate([
        {
            "$group": {
                "_id": { 
                    "name1": "$name1",
                    "name2": "$name2",
                }, 
                "expanded": { 
                    "$push": { 
                        "name1": "$name1", 
                        "name2": "$name2", 
                    } 
                },
                "count": { "$sum": 1 } 
            } 
        },
        { "$sort": { "count": -1 } },
        {
            $unwind: {
                path: '$expanded',
                includeArrayIndex: 'count'
            }
        }
    ]);

预期结果

Name|Count|Rank
Google|3|1 
FB|2|2
Yahoo|1| 3

数据库架构:

{
    "_id" : 1.0,
    "name1" : "Yahoo",
    "name2" : "Google",
    "salary" : 1000.0
}

/* 2 */
{
    "_id" : 2.0,
    "name1" : "FB",
    "name2" : "Google",
    "salary" : 2000.0
}

/* 3 */
{
    "_id" : 3.0,
    "name1" : "Google",
    "name2" : "FB",
    "salary" : 1500.0
}

2 个答案:

答案 0 :(得分:1)

似乎您应该分别计算name1name2,以便可以创建一个临时的2元素数组,然后在该数组上运行$unwind。另外,要获取rank,您必须null之前$group才能获得所有组的单个数组,请尝试:

db.collection.aggregate([
    {
        $project: {
            key: [ "$name1", "$name2" ]
        }
    },
    {
        $unwind: "$key"
    },
    {
        $group: {
            _id: "$key",
            count: { $sum: 1 }
        }
    },
    {
        $sort: {
            count: -1
        }
    },
    {
        $group: {
            _id: null,
            groups: { $push: "$$ROOT" }
        }
    },
    {
        $unwind: {
            path: '$groups',
            includeArrayIndex: 'rank'
        }
    },
    {
        $project: {
            _id: 0,
            name: "$groups._id",
            rank: { $add: [ "$rank", 1 ] },
            count: "$groups.count"
        }
    }
])

Mongo Playground

答案 1 :(得分:1)

  

尝试

db.company.aggregate([
{
  $group: {
    _id:null,
    names1: {$push: "$name1"},
    names2: {$push:"$name2"},
  }
},
{
  $project: {
    _id: 0,
    names:{$concatArrays: ["$names1", "$names2"]}
  }
},
{$unwind: "$names"},
{$sortByCount: "$names"},
{$addFields:{name: "$_id"}},
{
  $group : {
    _id: null,
    records : { $push : {count : "$count", name : "$name"}}
  }
},
{
  $project: {
   total_docs: {$size: "$records"},
   records: 1
  }
},
{$unwind: "$records"},
{
  $project: {
    _id: 0,
    name: "$records.name",
    count:"$records.count",
    rank: {
      $add:[
        {
          $subtract:["$total_docs", "$records.count"]
        }, 1]
    }
  }
}])