MongoDB在列表顶部返回特定值

时间:2018-02-06 09:26:07

标签: mongodb sorting

我的排序应该按国家/地区排序 - “India”始终位于顶部,其余按字母排序。

如何使用 mongo-shell命令实现这一目标?

{
        "_id" : ObjectId("5a797000287389c34c70c525"),
        "Country" : "World",
        "Population" : "7550262101"
}
{
        "_id" : ObjectId("5a797000287389c34c70c526"),
        "Country" : "China",
        "Population" : 1409517397
}
{
        "_id" : ObjectId("5a797000287389c34c70c527"),
        "Country" : "India",
        "Population" : 1339180127
}
{
        "_id" : ObjectId("5a797000287389c34c70c528"),
        "Country" : "USA",
        "Population" : 324459463
}
{
        "_id" : ObjectId("5a797000287389c34c70c529"),
        "Country" : "Indonesia",
        "Population" : 263991379
}

1 个答案:

答案 0 :(得分:-1)

在参考Dynamic Sticky Sorting in Mongo for a simple value or list上的另一篇文章后,我找到了达到预期效果的方法

db.population.aggregate(
[
  {$project: {
    Country: 1,
    Population: 1,
    sticky: {$cond: [{$eq: ['$Country', 'India']}, 1, 0]}
  }},
  {$sort: 
    {sticky: -1,
    Country: 1}
  },
  {$project: {
    Country: 1,
    Population: 1,
  }}
])

上述查询的结果是

{ "_id" : ObjectId("5a797000287389c34c70c527"), "Country" : "India", "Population" : 1339180127 }
{ "_id" : ObjectId("5a797000287389c34c70c525"), "Country" : "World", "Population" : "7550262101" }
{ "_id" : ObjectId("5a797000287389c34c70c526"), "Country" : "China", "Population" : 1409517397 }
{ "_id" : ObjectId("5a797000287389c34c70c528"), "Country" : "USA", "Population" : 324459463 }
{ "_id" : ObjectId("5a797000287389c34c70c529"), "Country" : "Indonesia", "Population" : 263991379 }