1

I am new to MongoDB and I am investigating what currently seems like an anomaly.

Consider the below script executed on MongoDB 2.6.1:

var codes = [
  "abc1001",
  "abc1002",
  "abc1003",
  "abc1004",
  "abc1005"];

var codesCount = codes.length;

for (var i = 0; codesCount > i; i++) {
  var insertCode = codes[i];
  var result = db.allcodes.findOne({ code: insertCode });
  if (result == null) {
    db.allcodes.insert({ code: insertCode });
  }
}

So inserting 5 new codes into 'allcodes' collection. Now there were about 1000 other codes (documents) in the collection prior to script execution. In one of the environments (copies of the MongoDB), the above script inserted one of the codes, lets say 'abc1001' in the middle of the collection, and all others towards the end, as was expected. To illustrate this, here is the snippet of results of pulling all the documents from the collection after the insert:

.
.
.
abc500
abc501
abc1001
abc502
abc503
.
.
.
abc1002
abc1003
abc1004
abc1005

So one code got inserted in the middle of the collection, and others at the end. Now I havent been able to reproduce this issue, as re-executing this script always inserted all 5 codes at the end of the collection. My question is what could be reason the document was inserted in the middle of the collection that time, and not towards the end, like all on all other attempts?

Appreciate all your comments.

fed1999
  • 79
  • 1
  • 5
  • What issue? Ordering of documents is only guaranteed if you use [.sort()](https://docs.mongodb.org/manual/reference/method/cursor.sort/) – Markus W Mahlberg Mar 23 '16 at 19:41
  • 1
    Read that question. It will explain you what is wrong: [How does MongoDB sort records when no sort order is specified?](http://stackoverflow.com/questions/11599069/how-does-mongodb-sort-records-when-no-sort-order-is-specified) – Bonanza Mar 23 '16 at 19:53

1 Answers1

1

In a nutshell, there may appear 'gaps' in your collection layout on disk (it we are talking about usual not 'capped' collections, which is almost always the case).

It usually happens due to one of 2 reasons:

  1. A document is removed from the middle of a collection.
  2. A document is updated in such way, that it doesn't fit its allocated space anymore. MongoDB allocates a new place for this document and moves it.

When you make an insert operation, the chances are that MongoDB will try to put your new document to one of these gaps and succeed with it.

If you want to maintain any kind of ordering, use sort() operation on the cursor. And don't forget to create a correspondent index first.

Roman
  • 64,384
  • 92
  • 238
  • 332