0

This is what I get now:

> db.collection_name.findOne()
{
    "_id" : ObjectId("whatever")
    "c" : "a value"
    "a" : "a value"
    "b" : "a value"
}

Is there any function that I could use so that I can see the document's fields in lexicographic order (on a find() or findOne())? I would like to see:

> db.collection_name.findOne().something()
{
    "_id" : ObjectId("whatever")
    "a" : "a value"
    "b" : "a value"
    "c" : "a value"
}
rwg05
  • 127
  • 6

1 Answers1

1

since a document in JS is an associative map

var d = db.collection_name.findOne()
var sorted = {}
var keys = Object.keys(d).sort()
for (i = 0; i < keys.length; i++) {   
    key = keys[i];   
    sorted[key] = d[key]; 
 }

, you can sort it's keys and copy the ordered fields into a new document (sorted in that case)

Ori Dar
  • 18,687
  • 5
  • 58
  • 72