The ordering you're observing the shell is actually just coincidental and it's not guaranteed that MongoDB will continue to order those document fields that way every time. The database is actually just ordering those fields in an fashion that best suits its own needs and this ordering has the potential to change with every update that causes that document to grow.
When performing update operations that increase the document size beyond the allocated space for that document, the update operation relocates the document on disk and may reorder the document fields depending on the type of update
All that said, while you shouldn't rely on field order within the document, there are certain types of fields that do perserve order for their respective values. Fields that contain array values are guaranteed to perserve ordering.
For example, given this document:
{
_id: foo,
a: 1,
b: 2,
c: [1,2,3]
}
There is no guarantee about the order of a, b, and c within the document. However, the value of c (eg. [1,2,3]) is guaranteed to perserve its order. As a result, operations like the following will perserve the array's order.
db.test_coll.update({_id: foo}, { $push: {c: 5} })
{
_id: foo,
a: 1,
b: 2,
c: [1,2,3,5]
}
db.test_coll.update({_id: foo}, { $pop: {c: -1} })
{
_id: foo,
a: 1,
b: 2,
c: [2,3,5]
}
db.test_coll.update({_id: foo}, { $pop: {c: 1} })
{
_id: foo,
a: 1,
b: 2,
c: [2,3]
}