Problem on sort of Collection ID!

1- Insert data with Auto ID

    {name:'a'},
    {name:'b'},
    {name:'c'},
    {name:'d'},

But don’t show in order with .find({}, {sort: {_id: 1}})

2- Insert data with Sequence ID

    {_id: '8', name:'a'},
    {_id: '9', name:'b'},
    {_id: '10', name:'c'},
    {_id: '11', name:'d'},

But still don’t work, result

    {_id: '10', name:'c'},
    {_id: '11', name:'d'},
    {_id: '8', name:'a'},
    {_id: '9', name:'b'},

Please help and advice me :blush:

Actually it works properly. They are strings, not numbers.

Excuse me, Could we solve about this?

Change from

    {_id: '10', name:'c'},
    {_id: '11', name:'d'},
    {_id: '8', name:'a'},
    {_id: '9', name:'b'},

to

    {_id: 10, name:'c'},
    {_id: 11, name:'d'},
    {_id: 8, name:'a'},
    {_id: 9, name:'b'},

But you should not do this. If I was you, I wouldn’t overwrite the mongodb _id

1 Like

Could we convert String to Number in mongo _id?
Or we create other field, Eg: idNumber?

Or we create other field , Eg: idNumber?

You should create the field with the sort you need.

While you did the right thing by using ID to sort if it’s really your only key, using an auto ID and then interpreting it with a sort is a bad idea. You can’t really do both.

thanks for all, :sunny:

Depending on who inserts into the database and at what rate, you could either simply use a timestamp on insertion or do a simulation of an autoincrementing field.

The timestamp method is way easier but at a high rate of insertions it can lead to several documents having the same timestamp.

The AutoIncrement way is a bit more cumbersome as MongoDB doesn’t have an innate ability to do that - someone correct me if I’m wrong there.
Basically, you’ll first have to search for the last index, increment it by one and then insert a new document with the new index.

However, at a high rate of insertions this may run into the same problem as the timestamps.

You may try this, however, using the module mongodb-autoincrement on the server:

const autoIncrement = require("mongodb-autoincrement");

autoIncrement.setDefaults({
    field: 'sortingIndex'
});

yourMethod = (newData, callback) => {
    autoIncrement.getNextSequence(YourCollection.rawDatabase(), 
                                  "YourCollection", 
                                  (err, autoIndex) => {
                                      newData.sortingIndex = autoIndex;
                                      YourCollection.insert(newData);
                                  });
}

I did not try that piece of code, though.