2013-07-09 47 views
0

我有一个蒙戈集合与文档喜欢 -蒙戈排序嵌套数组中的多个字段

{ 
_id : 1abc, 
'data' :'blah', 
'createdDate' : ISODate("2013-05-26T01:34:10Z"), 
'a': [ 
    { 
     _id : a1adas, 
     'createdDate' : ISODate("2013-05-26T01:35:10Z"), 
     'b':[ 
       { 
        _id : aadaasd 
        'createdDate' : ISODate("2013-05-26T01:37:10Z"), 
       } 
      ] 
    } 
] 

}

我需要按时间倒序排列的文件进行排序,以便与文档最先创建的日期,在任何级别上都是第一个。

到目前为止,我有这个查询,我不确定是否按预期工作。

db.collection.find({'data':'blah'}).sort({'createdDate':-1, 'a.createdDate': -1, 'a.b.createdDate': -1 }).explain(); 

我想知道是否有更高效的方式来执行这样的排序。

回答

2

你的查询没有做你想做的事。在多个字段上的MongoDB排序将依次处理每个字段,而不是所有三个字段在一起。例如,我插入了一些测试文档到一个集合的,我已经跑了类似的排序:

> db.numbers.find().sort({ a : -1, b : -1, c : -1 }) 
{ doc : "doc1", "a" : 13, "b" : 5, "c" : 7 } 
{ doc : "doc2", "a" : 12, "b" : 20, "c" : 91 } 
{ doc: "doc3", "a" : 2, "b" : 50, "c" : 700 } 

“doc3的”具有的最低值,所以它返回最后。然而,它在这个领域的任何领域也是最高的,所以理论上我们希望它是第一个返回的东西。我们可以使用MongoDB的aggregation framework做到这一点:

db.numbers.aggregate(
{ $project : { 
    _id : 1, 
    a : 1, 
    maxNum : { $cond: [{ $gte : [ "$b", "$c" ]}, "$b" , "$c" ]} // max of b, c 
    }}, 
{ $project : { 
    _id : 1, 
    maxNum : { $cond: [{ $gte : [ "$a", "$maxNum" ]}, "$a" , "$maxNum" ]} // max of a, b, c 
    }}, 
{ $sort : { maxNum : -1 } } 
) 

这种聚合的查询将改变你的数据转化为在那里能够准确地对您的排序方式。但是,要看到它的表现并不容易。聚合查询目前没有.explain()函数。