diff --git a/bulk.go b/bulk.go index 8dba1eb..edb306f 100644 --- a/bulk.go +++ b/bulk.go @@ -118,6 +118,14 @@ func (b *Bulk) Upsert(filter interface{}, replacement interface{}) *Bulk { return b } +// UpsertOne queues an UpsertOne operation for bulk execution. +// The update should contain operator +func (b *Bulk) UpsertOne(filter interface{}, update interface{}) *Bulk { + wm := mongo.NewUpdateOneModel().SetFilter(filter).SetUpdate(update).SetUpsert(true) + b.queue = append(b.queue, wm) + return b +} + // UpsertId queues an UpsertId operation for bulk execution. // The replacement should be document without operator func (b *Bulk) UpsertId(id interface{}, replacement interface{}) *Bulk { diff --git a/bulk_test.go b/bulk_test.go index 6a43294..d425914 100644 --- a/bulk_test.go +++ b/bulk_test.go @@ -41,3 +41,23 @@ func TestBulk(t *testing.T) { ast.Equal(int64(4), result.MatchedCount) } + +func TestBulkUpsertOne(t *testing.T) { + ast := require.New(t) + cli := initClient("test") + defer cli.Close(context.Background()) + defer cli.DropCollection(context.Background()) + + result, err := cli.Bulk(). + UpsertOne(bson.M{"name": "Jess"}, bson.M{operator.Set: bson.M{"age": 20}, operator.SetOnInsert: bson.M{"weight": 40}}). + UpsertOne(bson.M{"name": "Jess"}, bson.M{operator.Set: bson.M{"age": 30}, operator.SetOnInsert: bson.M{"weight": 40}}). + Run(context.Background()) + + ast.NoError(err) + ast.Equal(int64(0), result.InsertedCount) + ast.Equal(int64(1), result.ModifiedCount) + ast.Equal(int64(0), result.DeletedCount) + ast.Equal(int64(1), result.UpsertedCount) + ast.Equal(1, len(result.UpsertedIDs)) + ast.Equal(int64(1), result.MatchedCount) +}