1

I need to use integer numbers for my array object ID. now in mongoDB the default _id for array objects are ObjectId('62e10eb9150cd328edd6f6y3') and i need to change that to integer numbers. Can I know is that possible or not. If that possible please mention how to do that.

1 Answer 1

1

now in mongoDB the default _id for array objects are ObjectId('62e10eb9150cd328edd6f6y3')

This is not true, this is true for mongoose as it generates an ObjectId for each object by default - but this is not a MongoDB feature.

mongoose does not offer any alternatives as a feature, in your case using index of array as _id, but you can work around it by executing a slightly less efficient update using the aggregation pipeline syntax, like so:

const newArrayItem = { ... new array items };

db.collection.updateOne(
{},
[
  {
    "$set": {
      "items": {
        $concatArrays: [
          {
            $ifNull: [
              "$items",
              []
            ]
          },
          [
            {
              $mergeObjects: [
                newArrayItem,
                {
                  _id: {
                    $size: {
                      $ifNull: [
                        "$items",
                        []
                      ]
                    }
                  }
                }
              ]
            }
          ]
        ]
      }
    }
  }
])

Mongo Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.