The insert with _id value

Will my insert be successful if I provide an _id field with a value that does not exist on the DB

yes it will.
did you tried and it failed?
do you have an issue?

2 Likes

no, just checking…
thanks @steevej

you can insert anything into _id field

but if you don’t supply it then MongoDB will generate an ObjectId and insert that instead.

Hello and welcome to the community @Olufemi_Bolaji !

I think both @steevej and @Yilmaz_Durmaz have provided the answer here. Yes you can provide a custom _id field, and yes if you don’t supply one it will be generated for you.

However I’d like to focus on one part of your question:

Will my insert be successful if I provide an _id field with a value that does not exist on the DB

Actually you need to provide an _id that does not exist yet in the collection, as it’s supposed to be the document’s primary key. Otherwise the insert will fail with an E11000 duplicate key error message. For more information, see the _id field.

Best regards
Kevin

3 Likes