37 lines
835 B
Go
37 lines
835 B
Go
package mongo
|
|
|
|
import (
|
|
"context"
|
|
|
|
"go.mongodb.org/mongo-driver/v2/bson"
|
|
)
|
|
|
|
// UpdateSet search documents using filter and updates the first it finds using the $set operator.
|
|
func (c *MongoClient) UpdateSet(ctx context.Context, database, name string, filter, data bson.M) (bool, error) {
|
|
collection := c.GetCollection(database, name)
|
|
|
|
prepareForUpdateSet(data)
|
|
|
|
if err := c.DiscriminatorCheckAndApplyToFilter(ctx, name, filter); err != nil {
|
|
return false, err
|
|
}
|
|
|
|
if err := c.DiscriminatorOmitInData(name, data); err != nil {
|
|
return false, err
|
|
}
|
|
|
|
update := bson.M{ "$set": data }
|
|
updateResult, err := collection.UpdateOne(ctx, filter, update)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
changed := updateResult.ModifiedCount != 0
|
|
|
|
return changed, nil
|
|
}
|
|
|
|
func prepareForUpdateSet(data bson.M) {
|
|
ensureUpdatedAt(data)
|
|
}
|