0

I am trying to insert an array of 26 items in my mongodb database using following code:

const items = [item1, item2, ....., item26]
Model.remove({}).then(() => Model.insertMany(items));

When I run this for a local database, the order of items in the collection is as expected. But when I change my connection to a remote m-lab database, the items are not in a correct order in the database. It becomes something like item13...item26, item1...item12.

PS: I am doing this to run some tests.

nihartrivedi810
  • 333
  • 1
  • 2
  • 12
  • What do you mean they are not in the "correct" order? How are you determining the order? – Jason Cust Feb 22 '18 at 20:15
  • You may want to read [this](https://stackoverflow.com/questions/11599069/how-does-mongodb-sort-records-when-no-sort-order-is-specified). Relevant part: "By definition the sort defaults to undefined, and so is the return order of documents. If there is no query then it will use the natural order. The results are returned in the order they are found, which may coincide with insertion order (but isn't guaranteed to be) or the order of the index(es) used.". – mingos Feb 23 '18 at 00:55

1 Answers1

1

We can provide an "ordered" option to insertmany as true.

db.collection.insertMany(
   [ <document 1> , <document 2>, ... ],
   {
      writeConcern: <document>,
      ordered: <boolean>
   }
)

See the docs: https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/