2

I'm reviewing my MongoDB documents using Robo 3T, and I'd like to sort the keys in the document by their name.

My document might look like {"Y":3,"X":"Example","A":{"complex_obj":{}} and at the end I'd like the returned document to look like when I run a find query and apply a sort to it. {"A":{"complex_obj":{},"X":"Example","Y":3}

Is there a way to sort the returned keys / fields of a document? All the examples I see are for applying sort based on the value of a field, rather than the name of the key.

whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
ADataGMan
  • 449
  • 1
  • 7
  • 23

2 Answers2

1

There is a way but you won't like it. Technically you can do it with aggregation by converting objects to arrays, unwinding, sorting, grouping it back and converting the group to the object:

db.collection.aggregate([
  {
    $project: {
      o: {
        $objectToArray: "$$ROOT"
      }
    }
  },
  {
    $unwind: "$o"
  },
  {
    $sort: {
      "o.k": 1
    }
  },
  {
    $group: {
      _id: "$_id",
      o: {
        $push: "$o"
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: {
        $arrayToObject: "$o"
      }
    }
  }
])

but you don't want to do it. Too much hassle, too expensive, too little benefits.

Mongo by design preserve order of keys as they were inserted. Well, apart from _id, and few other edge cases.

Alex Blex
  • 34,704
  • 7
  • 48
  • 75
1

Not sure why the order of field does matter in a JSON document but you can try below aggregation query :

db.collection.aggregate([
    {
      $project: { data: { $objectToArray: "$$ROOT" } }
    },
    {
      $unwind: "$data"
    },
    {
      $sort: { "data.k": 1 }
    },
    {
      $group: { _id: "_id", data: { $push: "$$ROOT.data" } }
    },
    {
      $replaceRoot: { newRoot: { $arrayToObject: "$data" } }
    },
    {
      $project: { _id: 0 }
    }
   ])

Test : mongoplayground

whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
  • 1
    In this scenario I'm using a GUI tool to inspect a single document as a representative to see what the content might look like as I work through each document. By having it sorted, it makes it easier to track down a field I'd seen before than if it's in the original order. – ADataGMan May 21 '20 at 23:41