对多键索引字段进行Mongo db排序

时间:2016-12-12 09:34:37

标签: mongodb sorting indexing

我正在浏览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

1 个答案:

答案 0 :(得分:2)

好吧,结果似乎没有遵循任何顺序,但实际上它们是。在您的第一个排序{ratings:1}中,这里发生的是结果按评级中的最小元素排序。由于这些是您的清单:

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

因此列表[ 10, 6, 1 ]最小元素为1,列表[ 2, 3, 4 ]最小元素为2,列表[ 5, 8, 9 ]最小元素为5 }。所以结果以这种方式排序。

按降序排序时,会按照评分中的最大元素进行相同的顺序。

希望这有帮助。

相关问题