Mongo Template - create or update

690 Views Asked by At

I have a collection that represents items, The collection has multiple indexes (not one unique id). model looks something like:

data class Item {
    _id
    customer_id
    item_type: (game / movie / equipment)
}

I wanna create a query that uses these indexes to find or create, for example:

val item: Item
mongoTemplate.findOrCreate(customer_id: x, item_type: y, item)

I can of course guarantee that there wont be 2 items with same customer_id and type.

1

There are 1 best solutions below

0
On BEST ANSWER

You can create a function like this:

fun MongoTemplate.findOrCreate(customer_id: String, item_type: String): Item {
        val query = Query.query(
            Criteria().andOperator(
                Criteria.where("customer_id").`is`(customer_id),
                Criteria.where("item_type").`is`(item_type)
            )
        )
        
        return findOne(query, Item::class.java, "collectionName")
            ?: insert(Item(customer_id, item_type), "collectionName")
    }

MongoTemplate.findOne will return the object or null if it is not found, if null we use the MongoTemplate.insert to insert the new object. Insert will also return the object.

You would call this function like this:

val item: Item = mongoTemplate.findOrCreate(customer_id: x, item_type: y)