Skip to content

Commit

Permalink
feat: add upsert one in bulk (#256)
Browse files Browse the repository at this point in the history
  • Loading branch information
cloudingcity authored Oct 4, 2022
1 parent 06f8aaf commit 19f1bba
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
8 changes: 8 additions & 0 deletions bulk.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
20 changes: 20 additions & 0 deletions bulk_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit 19f1bba

Please sign in to comment.