2016-08-14 132 views
1

什么是一个集合中的下列文件进行排序的最佳方式:猫鼬:排序

{"topic":"11.Topic","text":"a.Text"} 
{"topic":"2.Topic","text":"a.Text"} 
{"topic":"1.Topic","text":"a.Text"} 

我使用以下

find.(topic:req.body.topic).(sort({topic:1})) 

,但不工作(因为字段是字符串,而不是数字,所以我得到的):

{"topic":"1.Topic","text":"a.Text"}, 
{"topic":"11.Topic","text":"a.Text"}, 
{"topic":"2.Topic","text":"a.Text"} 

,但我想获得:

{"topic":"1.Topic","text":"a.Text"}, 
{"topic":"2.Topic","text":"a.Text"}, 
{"topic":"11.Topic","text":"a.Text"} 

我读了另一篇文章here,这将需要猫鼬不具备的复杂排序。那么这个架构可能没有真正的解决方案?

你的帮助是极大的赞赏

+1

它的工作很大。你的主题是字符串,正按照这种方式排序。 – yarons

+0

'.sort('topic')' –

+0

这不起作用,因为正如我在我的问题中所述,主题被排序为字符串,所以我得到1,11,2 ... – qts

回答

0

我会建议你让你的topic申请作为type : Number,并创建另一个领域topic_text

您的架构看起来像:

var documentSchema = new mongoose.Schema({ 

    topic : Number, 
    topic_text : String, 
    text : String 

}); 

普通文件将是这个样子:

{document1:[{"topic":11,"topic_text" : "Topic" ,"text":"a.Text"}, 
     {"topic":2,"topic_text" : "Topic","text":"a.Text"}, 
     {"topic":1,"topic_text" : "Topic","text":"a.Text"}]} 

因此,你将能够使用.sort({topic : 1}),并得到你想要的结果。 ,同时使用topic值,将topic_text附加到它。

find(topic:req.body.topic).sort({topic:1}).exec(function(err,result) 
{ 
    var topic = result[0].topic + result[0].topic_text;//use index i to extract the value from result array. 
}) 
+0

你的意思是创建另一个字段,如下所示:{“topic_number”:1,“topic”:“Topic”,“text”:“a.Text”}?我可以做到这一点,但想知道是否有一个不那么繁琐的方式 – qts

+0

我的意思是只保留主题字段作为数字1,2,..当您使用主题值创建另一个变量,附加主题编号和“.Topic”。 –

+0

请检查我编辑的答案 –

0

如果你不想(或者甚至不能够)更改文件的形状,以包括话题数量,那么你可以达到你想要的与聚合框架排序数字字段。
下面的流水线基本上将'11.Topic'这样的主题字符串拆分为点'。'。然后将结果数组的第一部分前缀为固定数量的前导零,以便按这些字符串排序将导致“模拟”数字排序。
但请注意,此管道使用$split$strLenBytes运算符,它们非常新,因此您可能需要更新mongoDB实例 - 我使用的是3.3.10版。

db.getCollection('yourCollection').aggregate([ 
    { 
     $project: { 
      topic: 1, 
      text: 1, 
      tmp: { 
       $let: { 
        vars: { 
         numStr: { $arrayElemAt: [{ $split: ["$topic", "."] }, 0] } 
        }, 
        in: { 
         topicNumStr: "$$numStr", 
         topicNumStrLen: { $strLenBytes: "$$numStr" } 
        } 
       } 
      } 
     } 
    }, 
    { 
     $project: { 
      topic: 1, 
      text: 1, 
      topicNumber: { $substr: [{ $concat: ["_0000", "$tmp.topicNumStr"] }, "$tmp.topicNumStrLen", 5] }, 
     } 
    }, 
    { 
     $sort: { topicNumber: 1 } 
    }, 
    { 
     $project: { 
      topic: 1, 
      text: 1 
     } 
    }  
]) 

Working pipeline