Is there a way to sort the order of columns in mongodb?

Viewed 523

I have closed this question since I made it unclear

I am learning MongoDB and I've encountered a thing that mildly annoys me.

Let's say I got this collection:

[
  {
    _id: ObjectId("XXXXXXXXXXXXXX"),
    name: "Tom",
    followers: 10,
    active: true
  },
  {
    _id: ObjectId("XXXXXXXXXXXXXX"),
    name: "Rob",
    followers: 109,
    active: true
  },
  {
    _id: ObjectId("XXXXXXXXXXXXXX"),
    name: "Jacob",
    followers: 2,
    active: false
  }
]

and I rename the name column to username with the command:

db.getCollection('users').update({}, { $rename: { "name" : "username" }}, false, true)

now the username property is at the end of the record, example:

[
  // ... rest of collection has the same structure
  {
    _id: ObjectId("XXXXXXXXXXXXXX"),
    followers: 109,
    active: true,
    username: "Rob"
  }
  //  ... rest of collection has the same structure
]

How do I prevent this from happening or how do I place them in a specific order? This is infuriating to work with in Robo/Studio 3T. I've got a collection with about 15 columns which are now out of order which in the GUI because of this

2 Answers

The $rename operator logically performs an $unset of both the old name and the new name, and then performs a $set operation with the new name. As such, the operation may not preserve the order of the fields in the document; i.e. the renamed field may move within the document.

Documentation

It is the behaviour from version 2.6

Since it is JSON based, you can get any field easily. And you have very less columns.

Keys in JSON objects are in their very nature unordered. See RFC 4627 which defines JSON, section 1 "Introduction":

An object is an unordered collection of zero or more name/value
pairs, where a name is a string and a value is a string, number,
boolean, null, object, or array.

(Emphasis mine)

Therefore, it would even be correct, if you wrote

{
    "name": "Joe",
    "city": "New York"
}

and got back

{
    "city": "New York",
    "name": "Joe"
}
Related