Last active
April 4, 2021 18:30
-
-
Save iampato/b07578b447d92e2ece7307d7b93c8ced to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type User struct { | |
ID primitive.ObjectID `json:"id,omitempty" bson:"_id,omitempty"` | |
FirstName string `json:"first_name" bson:"first_name" ` | |
LastName string `json:"last_name" bson:"last_name" ` | |
EmailAddress string `json:"email_address" bson:"email_address" ` | |
Password string `json:"password" bson:"password" ` | |
CreatedAt time.Time `json:"created_at" bson:"created_at" ` | |
UpdatedAt time.Time `json:"updated_at" bson:"updated_at" ` | |
} | |
// updateField | |
func updateField(id string, key string, value string) error{ | |
objID, _ := primitive.ObjectIDFromHex(id) | |
filter := bson.D{{"_id", objID}} | |
// 1. with set only | |
update := bson.D{{Key: "$set", Value: bson.M{key: value, "updated_at": time.Now()}}} | |
// 2. with push only | |
update2 := bson.D{{Key: "$push", Value: bson.M{key: value, "updated_at": time.Now()}}} | |
// 3. with push and set | |
update3 := bson.D{ | |
{Key: "$set", Value: bson.M{key: value, "updated_at": time.Now()}}, | |
{Key: "$push", Value: bson.M{"created_at": time.Now()}} | |
} | |
_, err := client.Database("database_name").Collection("database_table").UpdateOne( | |
context.Background(), | |
filter, | |
update, | |
) | |
if err != nil { | |
return err | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment