mongoDB在两个字段上排序

时间:2020-04-07 20:04:30

标签: mongodb mongodb-query aggregation-framework

我有一个mongodb文档,如下所示:

 {

        "match_key" : 44801,
        "total_points" : 10.00,


    },
    {
        "match_key" : 44901,
        "total_points" : 8.00,
    },
   {
        "match_key" : 44901,
        "total_points" : 7.00,
    },

   {
        "match_key" : 44901,
        "total_points" : 11.00,
    },
    {

    "match_key" : 44801,
    "total_points" : 7.00,


}

我想对以上文档进行排序,但希望将具有相同match_key的文档保持在一起。

实际结果:

 {
        "match_key" : 44901,
        "total_points" : 11.00,
    }
,
 {

        "match_key" : 44801,
        "total_points" : 10.00,


    },
{
        "match_key" : 44901,
        "total_points" : 8.00,
    },

{

    "match_key" : 44801,
    "total_points" : 7.00,


}

 {
        "match_key" : 44901,
        "total_points" : 6.00,
    },

但是您看到相同的匹配键不在一起。

预期结果:

{
        "match_key" : 44901,
        "total_points" : 11.00,
    },
{
        "match_key" : 44901,
        "total_points" : 8.00,
    },
{
        "match_key" : 44901,
        "total_points" : 7.00,
    },
{

        "match_key" : 44801,
        "total_points" : 10.00,


    },
{

        "match_key" : 44801,
        "total_points" : 6.00,


    },

具有same_match键的文档按降序排列。

这是我尝试做的事情:

 db.collection.aggregate(
    [
      { $match: { match_key:{$in:[44801,45910]}}},
      { $sort: {total_points:1,match_key:1} }
    ]
 )

这是这个问题的sql等效项,我正在尝试询问-Sort by most recent but keep together by another ID column

我的主要动机是对文档进行排序,并将具有相同match_key的文档保持在一起,但顺序 / **

1 个答案:

答案 0 :(得分:1)

您需要将此$sort分成两个阶段,如下所示:

db.collection.aggregate([
  {
    $match: {
      match_key: {
        $in: [
          44801,
          45910
        ]
      }
    }
  },
  {
    $sort: {
      total_points: -1
    }
  },
  {
    $sort: {
      match_key: -1
    }
  }
])

测试: MongoDB-Playground

注意::第一阶段是$match,因此我们应该很好地进行排序,但是即使我们需要进行两次排序,也请尝试将数据集保持为尽可能低,您需要在两个字段total_pointsmatch_key上有两个Single-field-index

问题: 因此,当您执行此操作时:{ $sort: {total_points:-1,match_key:1} }您的查询将首先在total_points :1字段上进行排序,如果它找到两个具有相同total_points值的文档,则将转到match_key:1将对那些文档进行排序两个文档以使它们井然有序。

问题示例:使用上面的复合排序,您将得到以下结果

  {
    "_id": ObjectId("5a934e000102030405000002"),
    "match_key": 44801,
    "total_points": 10
  },
  {
    "_id": ObjectId("5a934e000102030405000003"),
    "match_key": 45910,
    "total_points": 10
  },
  {
    "_id": ObjectId("5a934e000102030405000005"),
    "match_key": 44801,
    "total_points": 7
  }

如果您看到total_points是按顺序排序的,则第一优先级位于total_points上,因为有两个文档的"total_points": 10具有第二优先级match_key。无论如何,如果要排序为11->10->7,则需要对-1使用降序机制,而对1不使用降序机制(升序)。

相关问题