While Performing bulkWrite with custom _id (Long data type instead of Object), Mongo DB is returning duplicate key error.
Q1. How to fix this?
Q2. Is there a way to tell MongoDB to use LONG instead of ObjectId while inserting a document?
Hi @Ganapathi_Vaddadi1,
I’ve find it from the documentation:
You could try such a syntax and then readjust it to bulk inserts:
db.types.insertOne(
{
"_id": Long("1"),
"x":true ,
}
)
Regards
If you get
then it means you do try to insert a document with an _id that already exists with the same type and value. Mongo does not really care about what type you use for the _id, it just need to be unique. The issue is with your code. Your code must ensure you do not generate 2 _id with the same value. If you share your code with might be able to pinpoint the issue.
Just to illustrate the fact of uniqueness in type and value. Try
db.test.insertOne( { _id : 1 })
//
// works because _id of type number with value 1 does not exist
db.test.insertOne( { _id : "1" })
//
// works because _id of type string
db.test.aggregate( { $set : { type : { $type : "$_id" }}})
//
// to see types of your _id
db.test.insertOne( { _id : new Long( 1 ) } )
db.test.insertOne( { _id : new Double(1) } )
//
// both should fail because there is already
// _id with a number being 1 despite the fact that the type
// is not exactly the same. Oups. 8-(
Let’s dig deeper by what I means about not exactly the same.
db.test.deleteOne( { _id : new Double(1) } )
//
// works despite the fact that the type is "int" as seen
// in the aggregation
db.test.insertOne( { _id : new Double(1) } )
//
// if you run the above aggregation you will see that the internal
// is not 'double'.