0

I have the following document in a collection in my MongoDB database:

"_id":"5e2088563824e72ea5ee7095",
"image":"xxx",
"questions":[ 
    {
       "_id":"5e2088563824e72ea5ee70c3",
       "text":"test test test",
    },
    {
       "_id":"5e2088563824e72ea5ee70be",
       "text":"what is your age 1?",
    },
    {
      "_id":"5e2088563824e72ea5ee70b9",
      "text":"what is your gender 1?",
    },
    {
      "_id":"5e2088563824e72ea5ee70b4",
      "text":"what is your blood type 1?",
    },
    {
      "_id":"5e2088563824e72ea5ee70af",
      "text":"what is your blood type 1?",
    }
],
"__v":0

Without doing any type of sorting on the questions array, the document would always return like this which is the natural ascending order of the data entered.

What is strange is that the generated IDs are in reversed order as you can see:

key 0 => 5e2088563824e72ea5ee70c3
key 1 => 5e2088563824e72ea5ee70be
key 2 => 5e2088563824e72ea5ee70b9
key 3 => 5e2088563824e72ea5ee70b4
key 4 => 5e2088563824e72ea5ee70af

I expected the generated ID to match with the key of the array (ascending) so, it should be like:

key 0 => 5e2088563824e72ea5ee7096
key 1 => 5e2088563824e72ea5ee709b
key 2 => 5e2088563824e72ea5ee70a0
key 3 => 5e2088563824e72ea5ee70a5
key 4 => 5e2088563824e72ea5ee70aa

However, behaviour of the generated document IDs is normal like the auto-increment of MySQL (ascending). It's just the nested arrays that have the reversed order.

Is this a bug or is it the normal behavior? Why is it designed like this if this is normal?

  • MongoDB only generates ObjectIDs for _id (if not present), so ObjectIDs for your array are being added in your application code or ODM. Please edit your question to include a code snippet showing how you add elements to the array and indicate the specific versions of MongoDB server, driver, and framework/ODM (eg Mongoose) you are using. – Stennie Jan 16 at 19:42
  • Yes I'm using mongoose. There is really no special code to generate the array just a simple object like questions { text: 'abc' }and mongoose just generates the id – Michael Samuel Jan 16 at 21:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.