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.
- Sync
- Async
TigrisCollection<Catalog> catalog = tigrisDatabase.getCollection(Catalog.class);
TigrisAsyncCollection<Catalog> catalog = tigrisDatabase.getCollection(Catalog.class);
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.
- Sync
- Async
UpdateResponse response = catalog.update(
Filters.eq("id", 1),
UpdateFields.newBuilder().set("price", 65).build()
);
CompletableFuture<UpdateResponse> future = catalog.update(
Filters.eq("id", 1),
UpdateFields.newBuilder().set("price", 65).build()
);
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.
catalog.update(
Filters.or(
Filters.eq("id", 1),
Filters.eq("id", 4)),
UpdateFields.newBuilder().set("popularity", 9).build()
);
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.
catalog.update(
Filters.and(
Filters.eq("id", 4),
Filters.eq("id", 2)),
UpdateFields.newBuilder().set("popularity", 9).build()
);
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.
catalog.update(
Filters.and(
Filters.eq("name", "sneakers shoes"),
Filters.eq("name", "adidas")),
UpdateFields.newBuilder().set("price", 85).build()
);