简体   繁体   中英

Mongo DB reorder objects on insert

In my node js app Im using Mongo DB , and I have an Issue when Inserting something in database. When I add new record to collection objects beign reordered . Does anyone knows why is this happening ? Im doing insert like this

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

Actually , any operation on collection change the order of objects , does anyone knows why is this happening ?

MongoDB documents have padding space that is used for updates. If you make small changes to a document like adding/updating a small field there is a good chance that the size of the updated document will increase but will still fit into allocated space because it can use that padding. If the updated document does not fit in that space Mongo will move it to a new place on disk. Thus your documents might move a lot in the beginning until Mongo learns how much padding you would usually need to prevent such moves. You can also set higher padding to avoid documents being moved in the first place.

In either case you can't really rely on the insertion order to get sorted list of documents. If you want guaranteed order you need to sort. In your case you can sort by _id because it's a monotonically increasing counter which contains date and time details:

// in the order of insertion unless you got `_id` value externally
// (in your code, not auto assigned by Mongo) and doc with such ID
// was inserted much later.
// Sharding might also introduce tiny ordering mismatches
db.collection.find().sort( { '_id': 1 } );

// most recently inserted items first
db.collection.find().sort( { '_id': -1 } );

If you use capped collection the order of inserts will be preserved always, ie Mongo will never move documents. In that case you can use natural order sorting:

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

which is equivalent to sorting by _id as shown above.

Do not use natural order sorting with non-capped collections (regular collections) because it will not be reliable in presence of updates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM