2016-12-12 37 views
2

我正在通過mongo數據庫索引,並發現這一點,當我在多鍵字段上創建索引,並嘗試排序結果的行爲是奇怪的。
例如:Mongo db在多鍵索引字段排序

> db.testIndexes.find(); 
{ "_id" : ObjectId("584e6ca8d23d3b48f9cb819d"), "type" : "depart", "item" : "aaa", "ratings" : [ 5, 8, 9 ] } 
{ "_id" : ObjectId("584e6cb2d23d3b48f9cb819e"), "type" : "depart", "item" : "aaa", "ratings" : [ 2, 3, 4 ] } 
{ "_id" : ObjectId("584e6cbdd23d3b48f9cb819f"), "type" : "depart", "item" : "aaa", "ratings" : [ 10, 6, 1 ] } 

db.testIndexes.createIndex({ratings:1}); 

現在,如果我起訴這些查詢:

db.testIndexes.find().sort({ratings:1}).pretty(); 

結果是這樣的

{ 
    "_id" : ObjectId("584e6cbdd23d3b48f9cb819f"), 
    "type" : "depart", 
    "item" : "aaa", 
    "ratings" : [ 
      10, 
      6, 
      1 
    ] 
} 
{ 
    "_id" : ObjectId("584e6cb2d23d3b48f9cb819e"), 
    "type" : "depart", 
    "item" : "aaa", 
    "ratings" : [ 
      2, 
      3, 
      4 
    ] 
} 
{ 
    "_id" : ObjectId("584e6ca8d23d3b48f9cb819d"), 
    "type" : "depart", 
    "item" : "aaa", 
    "ratings" : [ 
      5, 
      8, 
      9 
    ] 
} 

和查詢

db.testIndexes.find().sort({ratings:-1}).pretty(); 

的結果是:

{ 
    "_id" : ObjectId("584e6cbdd23d3b48f9cb819f"), 
    "type" : "depart", 
    "item" : "aaa", 
    "ratings" : [ 
      10, 
      6, 
      1 
    ] 
} 
{ 
    "_id" : ObjectId("584e6ca8d23d3b48f9cb819d"), 
    "type" : "depart", 
    "item" : "aaa", 
    "ratings" : [ 
      5, 
      8, 
      9 
    ] 
} 
{ 
    "_id" : ObjectId("584e6cb2d23d3b48f9cb819e"), 
    "type" : "depart", 
    "item" : "aaa", 
    "ratings" : [ 
      2, 
      3, 
      4 
    ] 
} 

由於結果似乎並沒有遵循和秩序,所以任何人都可以幫助mongo如何排序這些結果。

感謝
Virendra

回答

2

那麼它似乎是結果不遵循任何命令,但實際上他們是。在您的第一個排序{ratings:1}中,這裏發生的是結果按評分中的最小元素排序。由於這些都是你的清單:

[ 10, 6, 1 ] [ 2, 3, 4 ] [ 5, 8, 9 ] 

所以列表[ 10, 6, 1 ]最小的元素是1,列表[ 2, 3, 4 ]最小的元素是2和列表[ 5, 8, 9 ]最小的元素是5。所以結果以這種方式排序。

當您按降序排序時,會發生相同的順序,但通過評級中的最大元素進行排序。

希望這會有所幫助。

+0

Thanks @ guvmaor86 this helps – viren