【问题标题】:Mongo Template - create or updateMongo 模板 - 创建或更新
【发布时间】:2020-10-14 13:59:39
【问题描述】:

我有一个代表项目的集合, 该集合有多个索引(不是一个唯一的 id)。 模型看起来像:

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

我想创建一个使用这些索引来查找或创建的查询,例如:

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

我当然可以保证不会有 2 件商品具有相同的 customer_id 和 type。

【问题讨论】:

    标签: mongodb kotlin mongotemplate


    【解决方案1】:

    你可以像这样创建一个函数:

    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 将返回对象,如果找不到则返回 null,如果为 null,我们使用 MongoTemplate.insert 插入新对象。插入也会返回对象。

    你可以这样调用这个函数:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-01
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      • 2020-06-15
      相关资源
      最近更新 更多