2013-05-11 93 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字段上創建索引將使代碼在任何情況下都更快。