Skip to content

Commit

Permalink
Generate new ObjectID only when required
Browse files Browse the repository at this point in the history
  • Loading branch information
adhocore committed Dec 5, 2023
1 parent a8fa12a commit 4cfa230
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 2 deletions.
2 changes: 1 addition & 1 deletion mongo/bulk_write.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion mongo/collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
3 changes: 3 additions & 0 deletions mongo/mongo.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit 4cfa230

Please sign in to comment.