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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With