2

My document looks like this

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

How one can sort the data present in nested_documents?
Expected answer is shown below:

nested_documents: [ { x:"-1", y:"3" },{ x:"1", y:"2" },{ x:"2", y:"3" }]
Sachin
  • 3,424
  • 3
  • 21
  • 42
  • This might actually be faster in your client code to than using the aggregation framework, depending on the size of your subdocuments of course. – Sammaye Mar 08 '13 at 13:25

1 Answers1

1

To do this you would have to use the aggregation framework

db.test.aggregate([{$unwind:'$nested_documents'},{$sort:{'nested_documents.x': 1}}])

this returns

"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

Hope this helps