2013-03-08 48 views
2

我的文件看起來像這樣在MongoDb中,如何應用文檔中存在的排序內部字段?

{ 
    field1: somevalue, 
    name:xtz 


    nested_documents: [ // array of nested document 
    { x:"1", y:"2" }, // first nested document 
    { x:"2", y:"3" }, // second nested document 
    { x:"-1", y:"3" }, // second nested document 
    // ...many more nested documents 
    ] 
} 

如何可以存在於nested_documents對數據進行排序?
預期的答案如下:

nested_documents: [ { x:"-1", y:"3" },{ x:"1", y:"2" },{ x:"2", y:"3" }] 
+0

這實際上在客戶端代碼中可能比使用聚合框架更快,當然這取決於子文檔的大小。 – Sammaye 2013-03-08 13:25:29

回答

1

要做到這一點,你將不得不使用聚合框架

db.test.aggregate([{$開卷: '$ nested_documents'},{ $排序:{ 'nested_documents.x': 1}}])

此返回

"result" : [ 
    { 
      "_id" : ObjectId("5139ba3dcd4e11c83f4cea12"), 
      "field1" : "somevalue", 
      "name" : "xtz", 
      "nested_documents" : { 
        "x" : "-1", 
        "y" : "3" 
      } 
    }, 
    { 
      "_id" : ObjectId("5139ba3dcd4e11c83f4cea12"), 
      "field1" : "somevalue", 
      "name" : "xtz", 
      "nested_documents" : { 
        "x" : "1", 
        "y" : "2" 
      } 
    }, 
    { 
      "_id" : ObjectId("5139ba3dcd4e11c83f4cea12"), 
      "field1" : "somevalue", 
      "name" : "xtz", 
      "nested_documents" : { 
        "x" : "2", 
        "y" : "3" 
      } 
    } 
], 
"ok" : 1 

希望這會有所幫助

+0

感謝您的回覆。但是,我只想要一個對象與nested_documents中的元素進行排序 – Sach 2013-03-09 16:45:38

相關問題