Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
⌂ 换网址