Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB field order and document position change after update

Tags:

I am learning MongoDB and I noticed that whenever I do an update on a document the field being updated is pushed to the end of the order, so if I had something like:

db.collection.save({field1: value1, field2: value2, ..., field 10: value10}); db.collection.update({field1: value1}, {$set: {field2: new_value}}); 

then if you do:

db.collection.find(); 

it will display:

{ "field1":"value1", ..., "field10":"value10", "field2":"new_value"} 

You can see how the field order changes where the updated field is being pushed to the end of the document. In addition, the document itself is being pushed to the end of the collectoin. I know that it's a "schema-less" DB and it may not be a huge problem, but it just doesn't look "pretty" :). Is there a way to do an in-place update without changing the order?

like image 908
techexpert Avatar asked Feb 18 '11 21:02

techexpert


People also ask

Does MongoDB return documents in order?

MongoDB does not store documents in a collection in a particular order. When sorting on a field which contains duplicate values, documents containing those values may be returned in any order.

Does field order matter MongoDB?

Indexes store references to fields in either ascending ( 1 ) or descending ( -1 ) sort order. For single-field indexes, the sort order of keys doesn't matter because MongoDB can traverse the index in either direction.

How does update work in MongoDB?

MongoDB Update method is used to update the document from the collection, and the update method will update the value of the existing document. We have used a $set operator at the time of updating the document. We can update a single document by using an update or updateOne method.


1 Answers

MongoDB allocates space for a new document based on a certain padding factor. If your update increases the size of the document beyond the size originally allocated the document will be moved to the end of the collection. The same concept applies to fields in a document.

like image 65
Bernie Hackett Avatar answered Jan 08 '23 11:01

Bernie Hackett