Update Documents
The Update API is used to update existing documents that match the filters. Fields that need to be updated are specified when calling the API.
Example collection
The first step is to set up the collection object. All the operations on the collection is performed through this collection object.
catalogs := tigris.GetCollection[Catalog](catalogdb)
Now let's assume an e-commerce website that has the above collection catalog and has 5 products(documents) present in it.
id | name | price | brand | labels | popularity | reviews |
---|---|---|---|---|---|---|
1 | fiona handbag | 99.9 | michael kors | purses | 8 | {"author": "alice", "rating": 7} |
2 | tote bag | 49 | coach | handbags | 9 | {"author": "olivia", "rating": 8.3} |
3 | sling bag | 75 | coach | purses | 9 | {"author": "alice", "rating": 9.2} |
4 | sneakers shoes | 40 | adidas | shoes | 10 | {"author": "olivia", "rating": 9} |
5 | running shoes | 89 | nike | shoes | 10 | {"author": "olivia", "rating": 8.5} |
Update one
A simple update is by updating a document that matches the id which is the primary key of this collection.
In the above collection, let's say there is a need to modify the price
of a product that has an id assigned as 1.
_, err := catalogs.UpdateOne(ctx, filter.Gt("Id", 1), fields.Set("Price", 65))
if err != nil {
// handle error
}
Update many
The update many operation is used to update multiple documents. A common approach to achieving this is by using the logical OR
filter. The example below is
updating the popularity
score for two documents that have id 1 or 4.
_, err := catalogs.Update(ctx,
filter.Or(
filter.Eq("Id", 1),
filter.Eq("Id", 4)),
fields.Set("Popularity", 9))
if err != nil {
// handle error
}
Range update
Extending the example, what if there is a need to reset the popularity
score of a few products but these product ids
are continuous? In this case, a range update can be performed on this field. The following example is applying
range update on the id field.
_, err := catalogs.Update(ctx,
filter.And(
filter.Lte("Id", 4),
filter.Gte("Id", 2)),
fields.Set("Popularity", 9))
if err != nil {
// handle error
}
Filtering on multiple fields
There may be cases when you don't know the primary key value and instead wants to update a document by applying a
condition on the non-primary key field. The following example is increasing the price
of a product when the name
and brand match with the documents present in the collection.
_, err := catalogs.Update(ctx,
filter.And(
filter.Eq("Name", "sneakers shoes"),
filter.Eq("Brand", "adidas")),
fields.Set("Price", 85))
if err != nil {
// handle error
}