2013-05-11 94 views
0

MongoDB中记录商店这样获取基于类型和祖先场蒙戈DB记录

{_id:100,type:"section",ancestry:nil,.....} 
{_id:300,type:"section",ancestry:100,.....} 
{_id:400,type:"problem",ancestry:100,.....} 
{_id:500,type:"section",ancestry:100,.....} 
{_id:600,type:"problem",ancestry:500,.....} 
{_id:700,type:"section",ancestry:500,.....} 
{_id:800,type:"problem",ancestry:100,.....} 

我想为了获取记录这样 第一记录,其祖先是零 那么所有的记录,其父母是我们搜索第一条记录,其类型为“问题” 那么所有的纪录,其父母为我们搜索第一条记录,其类型为“部分”

预计产量

{_id:100,type:"section",ancestry:nil,.....} 
{_id:400,type:"problem",ancestry:100,.....} 
{_id:800,type:"problem",ancestry:100,.....} 
{_id:300,type:"section",ancestry:100,.....} 
{_id:500,type:"section",ancestry:100,.....} 
{_id:600,type:"problem",ancestry:500,.....} 
{_id:700,type:"section",ancestry:500,.....} 
+1

您可能需要在这里使用多个查询来获得您想要的效果 – Sammaye 2013-05-11 13:57:31

回答

1

试试这个MongoDB的shell命令:

db.collection.find().sort({ancestry:1, type: 1}) 

不同的语言,其中责令字典是不可用的,可以使用的2元组列表到之类的说法。像这样的东西(Python):

collection.find({}).sort([('ancestry', pymongo.ASCENDING), ('type', pymongo.ASCENDING)]) 
1

@vinipsmaker的回答很好。但是,如果_id是随机数或存在不属于树结构的文档,则它不能正常工作。在这种情况下,下面的代码将正确地工作:

function getSortedItems() { 
    var sorted = []; 
    var ids = [ null ]; 
    while (ids.length > 0) { 
     var cursor = db.Items.find({ ancestry: ids.shift() }).sort({ type: 1 }); 
     while (cursor.hasNext()) { 
      var item = cursor.next(); 
      ids.push(item._id); 
      sorted.push(item); 
     } 
    } 
    return sorted; 
} 

注意,该代码并不快,因为db.Items.find()将被执行n次,其中n是在树结构中的文件数量。

如果树形结构很大或者您会多次进行排序,则可以在查询中使用$in operator并在客户端对结果进行排序来优化此结构。

此外,在ancestry字段上创建索引将使代码在任何情况下都更快。