javascript - Mongo DB reorder objects on insert -


in node js app im using mongo db , , have issue when inserting in database. when add new record collection objects beign reordered . knows why happening ? im doing insert

collection.insert(object, {safe:true}, function(err, result) {     if (err) {         res.send({'error':'an error has occurred'});     } else {         // error     } }); 

actually , operation on collection change order of objects , knows why happening ?

mongodb documents have padding space used updates. if make small changes document adding/updating small field there chance size of updated document increase still fit allocated space because can use padding. if updated document not fit in space mongo move new place on disk. documents might move lot in beginning until mongo learns how padding need prevent such moves. can set higher padding avoid documents being moved in first place.

in either case can't rely on insertion order sorted list of documents. if want guaranteed order need sort. in case can sort _id because it's monotonically increasing counter contains date , time details:

// in order of insertion unless got `_id` value externally // (in code, not auto assigned mongo) , doc such id // inserted later. // sharding might introduce tiny ordering mismatches db.collection.find().sort( { '_id': 1 } );  // inserted items first db.collection.find().sort( { '_id': -1 } ); 

if use capped collection order of inserts preserved always, i.e. mongo never move documents. in case can use natural order sorting:

db.collection.find().sort( { $natural: 1 } ) 

which equivalent sorting _id shown above.

do not use natural order sorting non-capped collections (regular collections) because not reliable in presence of updates.


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -