Upsert is useful when it’s unclear whether the object to be updated is present or not.
An upsert query works like a regular update query if any document matching the where
clause exists. Otherwise, it acts as an insert query, i.e. it creates a new document with all the fields from the where
clause and update operators.
Space Cloud performs all upsert operations with snapshot level isolations so that all upserts are race safe.
Example: Insert a pokemon or update it if it’s already present:
mutation {
update_pokemons(
where: {_id: "1"},
set: {
name: "Pikachu",
type: "Electric"
}
op: upsert
) @mongo {
status
}
}
const whereClause = cond("_id", "==", "1")
const { status } = await db.upsert("pokemons")
.where(whereClause)
.set({name: "Pikachu", type: "Electric"})
.apply()