在MongoDb中,如何应用文档中存在的排序内部字段?

时间:2013-03-08 10:02:29

标签: 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" }]

1 个答案:

答案 0 :(得分: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

希望这有帮助