MongoDB: Upsert
Learn how to update an existing document or create it if missing.
We'll cover the following...
The Upsert
method verifies the presence of a resource with a matching identifier. In case of a match, an Update
method is executed; whereas if no match is found, it proceeds with a Create
action. Let us take a look at how we would build similar functionality in our MongoDB package.
The Update
method in MongoDB
Press + to interact
func (mongodb *Mongo) Update(query *db.Query) error {collection := mongodb.Client.Database(query.Database).Collection(query.Collection)context, cancel := context.WithTimeout(context.Background(), TIMEOUT)defer cancel()_, err := collection.UpdateOne(context,query.Filter,bson.D{{Key: "$set",Value: query.Object,}},options.Update().SetUpsert(true),)return err}
Most of this function looks almost identical to our ...