2012-08-03 93 views
0

我的文件看起來像這樣我怎樣才能嵌套文檔

{ 
    field1: somevalue, 
    field2: some other value, 


    nested_documents: [ // array of nested document 
    { ip: , session_id: , datetime: }, // first nested document 
    { ip: , session_id: , datetime: }, // second nested document 

    // ...many more nested documents 
    ] 
}, 

數組的第一個或最後一個文件的排序現場是否有可能獲得第一的datetime場的基礎上排序文檔,第二或nested_documents數組的最後一個文檔?如果是的話,我該怎麼做?

回答

1

對不起,這個問題很麻煩。我意識到有一個位置運算符可用於查詢數組,以便在排序和運行時嘗試運算符。

它可以通過使用位置運算符來完成。這是我做到了從外殼

sorting by the first nested document's field 

    db.sample.find().sort({"nested_documents.0.field_name" : -1}) // for descending order sort 

sorting by the second nested document's field 

    db.sample.find().sort({"nested_documents.1.field_name" : -1}) // for descending order sort 

Now for sorting by last document's field i have to keep track of length of the array so if length of array is 10 my query would be 

    db.sample.find().sort({"nested_documents.9.field_name" : -1}) // for descending order sort 
1

您可以使用positional operator由陣列中的一個特定的指數進行排序:

db.foo.drop(); 

db.foo.insert({ 
    _id: 1, 
    docs: [ 
     { date: new ISODate("2012-01-01T00:00:00Z") }, 
     { date: new ISODate("2010-01-01T00:00:00Z") } 
    ] 
}); 

db.foo.insert({ 
    _id: 2, 
    docs: [ 
     { date: new ISODate("2011-01-01T00:00:00Z") }, 
     { date: new ISODate("2013-01-01T00:00:00Z") } 
    ] 
}); 

jsTest.log("Sorting by first embedded document's date, ascending"); 
db.foo.find({}, { "docs.date": 1 }).sort({"docs.0.date": 1}).forEach(printjson); 

jsTest.log("Sorting by second embedded document's date, ascending"); 
db.foo.find({}, { "docs.date": 1 }).sort({"docs.1.date": 1}).forEach(printjson); 
+0

我沒有得到'從$ elemMatch查詢的動態位置不可用於排序'。 – lovesh 2012-08-03 17:59:50

+1

我的錯誤。我的意思是指[動態位置運算符](http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator),它允許您使用'$'來引用原始查詢中的字段用於更新。我只是提出了這個問題,因爲在另一個答案中提到了這個問題,這個問題已經被刪除了。 – jmikola 2012-08-03 18:27:52