如何使用MongoDB的聚合框架进行排序?

时间:2017-11-20 06:26:22

标签: mongodb scala aggregation-framework

我在 MongoDB 3.4 中有一个名为 Program 的文档,其中包含字段idprogram_nameno_of_students,如下所示:

Program
    {
     "id": ObjectId("5a06509859000089ebe6f2ab"),
     "program_name": "BBA",
     "no_of_students": "50+"    
    },
    {
     "id": ObjectId("5a06509859000089ebe6f3ac"),
     "program_name": "BIM",
     "no_of_students": "40-50"  
    },
    {
     "id": ObjectId("5a06509859000089ebe6f4ad"),
     "program_name": "MBA",
     "no_of_students": "100+"   
    },
    {
     "id": ObjectId("5a06509859000089ebe6f5ae"),
     "program_name": "MIM",
     "no_of_students": "60-75"  
    }

更新

在我的方案中, no_of_students 不能是整数,因为它可以包含类似值的范围,例如:

no_of_student

   "50-100"
   "100+"
   "10-50"
   "200-500"

在这里,我想基于no_of_students使用 MongoDB的聚合框架进行排序。应用排序后,结果应如下所示:

Program
    {
     "id": ObjectId("5a06509859000089ebe6f3ac"),
     "program_name": "BIM",
     "no_of_students": "40-50"  
    },
    {
     "id": ObjectId("5a06509859000089ebe6f2ab"),
     "program_name": "BBA",
     "no_of_students": "50+"    
    },
    {
     "id": ObjectId("5a06509859000089ebe6f5ae"),
     "program_name": "MIM",
     "no_of_students": "60-75"  
    },
    {
     "id": ObjectId("5a06509859000089ebe6f4ad"),
     "program_name": "MBA",
     "no_of_students": "100+"   
    }

1 个答案:

答案 0 :(得分:0)

您可以使用以下命令在mongo中进行排序:

db.collection.find(query,fiels).sort({**key**:1});

这里,1表示升序,-1表示降序。 在您的情况下,您可以使用以下方式对结果进行排序:

db.class.find({}).sort({no_of_students:1})

但是为了获得好结果,请将 no_of_student 存储为整数,而不是格式为“50+”或“40-50”