I have a MongoDB db consisting of one PRIMARY and one SECONDARY instance (replica set) on the same server. When i execute a insertMany() command :
let docsArray = []
for(i = 0; i <= 7; i++){
let docsArray.push(
{something: i}
);
}
await collection.insertMany(docsArray)
something odd happens. My primary server saves the data in the correct order(the one I have specified) ,whereas the SECONDARY instance saves the docs in some random way. I have tried inserting the documents one by one throught creating a session and a loop:
for(i = 0; i <= 7; i++){
let newDoc = something + i;
await newDoc.save({session});
}
still give the same result. Why is that? Can the solution be something connected with the Write Concern? Thanks in advance!!!
Documents in MongoDB collections are not ordered.
If you add some documents to a collection and execute a find without conditions on that collection, you might get the documents back in the order you inserted them or in a different order.
To get the documents in a particular order, request the order in the query.