diff --git a/mongo/bulk_write.go b/mongo/bulk_write.go index a7efd551e7..f054c1e7ac 100644 --- a/mongo/bulk_write.go +++ b/mongo/bulk_write.go @@ -171,7 +171,7 @@ func (bw *bulkWrite) runInsert(ctx context.Context, batch bulkWriteBatch) (opera if err != nil { return operation.InsertResult{}, err } - doc, _, err = ensureID(doc, primitive.NewObjectID(), bw.collection.bsonOpts, bw.collection.registry) + doc, _, err = ensureID(doc, primitive.NilObjectID, bw.collection.bsonOpts, bw.collection.registry) if err != nil { return operation.InsertResult{}, err } diff --git a/mongo/collection.go b/mongo/collection.go index ac173307ff..c7b2a8a113 100644 --- a/mongo/collection.go +++ b/mongo/collection.go @@ -256,7 +256,7 @@ func (coll *Collection) insert(ctx context.Context, documents []interface{}, if err != nil { return nil, err } - bsoncoreDoc, id, err := ensureID(bsoncoreDoc, primitive.NewObjectID(), coll.bsonOpts, coll.registry) + bsoncoreDoc, id, err := ensureID(bsoncoreDoc, primitive.NilObjectID, coll.bsonOpts, coll.registry) if err != nil { return nil, err } diff --git a/mongo/mongo.go b/mongo/mongo.go index 393c5b7713..47746ffd30 100644 --- a/mongo/mongo.go +++ b/mongo/mongo.go @@ -219,6 +219,9 @@ func ensureID( const extraSpace = 17 doc = make(bsoncore.Document, 0, len(olddoc)+extraSpace) _, doc = bsoncore.ReserveLength(doc) + if oid.IsZero() { + oid = primitive.NewObjectID() + } doc = bsoncore.AppendObjectIDElement(doc, "_id", oid) // Remove and re-write the BSON document length header.