在 mongodb 中对推送的数组进行排序

Rad*_*eed 5 mongoose mongodb aggregation-framework

我有一个像这样的 mongodb 结果。

[
  {
    "_id": {
      "_id": "57174838afb8eb97ccd409ca",
      "name": "Yet another position",
      "description": "description",
      "code": "11Y-WK"
    },
    "votes": [
      {
        "candidate": {
          "_id": "56f19694e84a6bf1b66ad378",
          "surname": "XXXXXXXXX",
          "firstName": "XXXXXXXXX",
          "middleName": "XXXXXXXXX",
          "othername": " XXXXXXXXX XXXXXXXXX",
          "sc_number": "071050"
        },
        "count": 3
      },
      {
        "candidate": {
          "_id": "56f19690e84a6bf1b66aa558",
          "surname": "XXXXXXXXX",
          "othername": "XXXXXXXXX XXXXXXXXX",
          "sc_number": "034837"
        },
        "count": 2
      },
      {
        "candidate": {
          "_id": "56f19690e84a6bf1b66aa2f3",
          "surname": "XXXXXXXXX",
          "othername": "XXXXXXXXX XXXXXXXXX",
          "sc_number": "008243"
        },
        "count": 4
      }
    ],
    "total_count": 9
  },
  {
    "_id": {
      "_id": "571747a8afb8eb97ccd409c7",
      "name": "Test Position",
      "description": "Description",
      "code": "10T-9K"
    },
    "votes": [
      {
        "candidate": {
          "_id": "56f19690e84a6bf1b66aa3b7",
          "surname": "XXXXXXXXX",
          "othername": "XXXXXXXXX",
          "sc_number": "044660"
        },
        "count": 1
      },
      {
        "candidate": {
          "_id": "56f19690e84a6bf1b66aa6ea",
          "surname": "XXXXXXXXX",
          "othername": "XXXXXXXXX",
          "sc_number": "062444"
        },
        "count": 5
      },
      {
        "candidate": {
          "_id": "56f1968fe84a6bf1b66aa03e",
          "surname": "XXXXXXXXX",
          "othername": "XXXXXXXXX",
          "sc_number": "042357"
        },
        "count": 3
      }
    ],
    "total_count": 9
  }
]
Run Code Online (Sandbox Code Playgroud)

我需要按count降序排序。

下面是返回上述结果的查询。我尝试过在所有阶段应用排序,但没有运气。

  Vote.aggregate([
{ "$match": { "_poll" : mongoose.mongo.ObjectID(req.query._poll) } },
{
  "$group": {
    "_id": {
      "_position": '$_position',
      "candidate": '$candidate'
    },
    "voteCount": { "$sum": 1 }
  }
},
{
  "$group": {
    "_id": "$_id._position",
    "votes": {
      "$push": {
        "candidate": "$_id.candidate",
        "count": "$voteCount"
      }
    },
    "total_count": { "$sum": "$voteCount" }
  }
},
{ "$sort": { "total_count": -1 } }
Run Code Online (Sandbox Code Playgroud)

我需要插入排序操作的地方,按计数按降序排序。

pro*_*r79 1

要在聚合期间对数组进行排序是一件有点棘手的事情。所以我要解决的问题是:

  1. 展开数组
  2. 应用排序
  3. 重新组合数组

请找到 mongo shell 代码,该代码应该给出此技术的概述:

var group = {$group:{_id:"$type", votes:{$push:"$value" }}}
var unwind={$unwind:"$votes"}
var sort = {$sort:{"votes":-1}}
var reGroup = {$group:{_id:"$_id", votes:{$push:"$votes" }}}
db.readings.aggregate([group,unwind,sort ,reGroup])
Run Code Online (Sandbox Code Playgroud)

欢迎任何评论!