0

If through mongo shell is used the following (for few documents 50 for example)

db.<collection>.insertMany(
[
  {
    "name": "some name 1",
    ...
  },
  {
   "name": "some name 2",
    ...
  },
  ...
  {
    "name": "some name N",
    ...
  }
])

I can confirm that through db.<collection_name>.find() the documents are shown in the exact same order how they were declared and inserted through db.<collection>.insertMany(). Until here it is expected and is fine for me.

I did realize the following, if the collection is empty, and if the same content shown above - keeping the same the order - is declared as follows within the import.js file for importation purposes:

[
  {
    "name": "some name 1",
    ...
  },
  {
   "name": "some name 2",
    ...
  },
  ...
  {
    "name": "some name N",
    ...
  }
]

Therefore, is used the same content and order but db.<collection>.insertMany() was removed/ignored.

So, then if is executed through the console/terminal the following command:

mongoimport --db some_db \
            --collection collection_name \
            --file /path/import.json \
            --jsonArray

I can confirm the importation process is accomplished but if db.<collection_name>.find() is executed then the documents are shown in a different order how they were declared and inserted through db.<collection>.insertMany() as the first approach.

How fix this? It is problematic for aggregations how $first and $last

Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
  • Does this help: https://stackoverflow.com/a/11599283/2282634 – Joe Dec 30 '21 at 22:54
  • @Joe The point is accomplish the importation process but keeping and respecting the order of the documents declared within the .json file - seems your link is mostly based after of the importation – Manuel Jordan Dec 30 '21 at 23:00
  • 3
    The point is the order that documents are returned is not explicitly defined. You may find that it happens to be insertion order for some cases, but that should not be relied upon. If you need the documents returned in a particular order, sort them. If you really need the insertion order to be honored, use the maintainInsertionOrder command line option. – Joe Dec 30 '21 at 23:05
  • Interesting, I used the `db..insertMany()` approach many times and even in many instances and always the order is respected. Let me research about the `maintainInsertionOrder` option. Thanks – Manuel Jordan Dec 30 '21 at 23:44
  • @Joe the `--maintainInsertionOrder` parameter works how expected, put your answer to to mark it how solved. Thanks for the quick and polite support! – Manuel Jordan Dec 31 '21 at 13:28

0 Answers0