如何按字段值对mongodb文档进行排序?

时间:2017-07-14 10:04:25

标签: mongodb sorting

假设我有一个带有以下架构的mongodb集合

{ "_id" : "1", "name" : "person1", "description" : "description1" }
{ "_id" : "2", "name" : "person2", "description" : "description2" }
{ "_id" : "3", "name" : "person3", "description" : "description3" }
{ "_id" : "4", "name" : "person1", "description" : "description4" }
{ "_id" : "5", "name" : "person2", "description" : "description5" }
{ "_id" : "6", "name" : "person4", "description" : "description6" }
{ "_id" : "7", "name" : "person3", "description" : "description7" }
{ "_id" : "8", "name" : "person2", "description" : "description8" }
{ "_id" : "9", "name" : "person3", "description" : "description9" }
{ "_id" : "10", "name" : "person1", "description" : "description10" }

我想按照以下顺序按人名值排序

  • person4
  • person2
  • person1
  • person3

    如何将它们变成这种形式?

    { "_id" : "6", "name" : "person4", "description" : "description6" }
    { "_id" : "2", "name" : "person2", "description" : "description2" }
    { "_id" : "8", "name" : "person2", "description" : "description8" }
    { "_id" : "5", "name" : "person2", "description" : "description5" }
    { "_id" : "1", "name" : "person1", "description" : "description1" }
    { "_id" : "4", "name" : "person1", "description" : "description4" }
    { "_id" : "10", "name" : "person1", "description" : "description10" }
    { "_id" : "7", "name" : "person3", "description" : "description7" }
    { "_id" : "3", "name" : "person3", "description" : "description3" }
    { "_id" : "9", "name" : "person3", "description" : "description9" }
    

    以下是SQL世界中的相同场景

    +----+---------+---------------+
    | id | name    | description   |
    +----+---------+---------------+
    |  1 | person1 | description1  |
    |  2 | person2 | description2  |
    |  3 | person3 | description3  |
    |  4 | person1 | description4  |
    |  5 | person2 | description5  |
    |  6 | person4 | description6  |
    |  7 | person3 | description7  |
    |  8 | person2 | description8  |
    |  9 | person3 | description9  |
    | 10 | person1 | description10 |
    +----+---------+---------------+
    

    所以我使用这个查询

    select id, name, description
    from test
    order by case when name like 'person4' then 1
    when name like 'person2' then 2
    when name like 'person1' then 3
    when name like 'person3' then 4 end
    

    给了我正确的结果

    +----+---------+---------------+
    | id | name    | description   |
    +----+---------+---------------+
    |  6 | person4 | description6  |
    |  2 | person2 | description2  |
    |  8 | person2 | description8  |
    |  5 | person2 | description5  |
    |  1 | person1 | description1  |
    |  4 | person1 | description4  |
    | 10 | person1 | description10 |
    |  7 | person3 | description7  |
    |  3 | person3 | description3  |
    |  9 | person3 | description9  |
    +----+---------+---------------+
    

    我们是否具有SQL order by case when then语句的等价物?或者在mongodb中实现这一目标的任何解决方案?

  • 0 个答案:

    没有答案