2

私のドキュメントは次のようになります

{
  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" }]
4

1 に答える 1

1

これを行うには、集約フレームワークを使用する必要があります

db.test.aggregate([{$ unwind:'$ nested_documents'}、{$ sort:{'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

お役に立てれば

于 2013-03-08T10:18:47.813 に答える