I’m trying to insert multiple data using a for-loop (there will be individual processing after each insertion). The _id for each should be auto-generated so I’m providing null in that field.
you should not supply any values. Null is a value so you should not
The error message does not match part of you post. You write
with an leading underscore but the error complains about
without the leading underscore. Have you redacted the error message? Is it _id or id? The only auto-generated field in native mongo is the top level _id. If you have an error with id rather than _id then you must have a unique index on that field. If you do, then you cannot have 2 documents with the same value and null is a value.
To conclude
Only top level _id is auto-generated
If you want top level _id to be auto-generated, you must not supply a value (and null is a value)
Yeah, I realized that after looking at the indexes. There was an unwanted index probably created from the earlier stages of the code. I should’ve created a reply instead of an edit. Let me mark your reply as the solution though. Thanks for the detailed explanation!