【问题标题】:MongoTemplate findAndModify get updated document countMongoTemplate findAndModify 获取更新的文档计数
【发布时间】:2016-10-14 17:10:04
【问题描述】:

我正在使用MongoTemplate实现一个方法,可以根据查询更新多个文档,并返回更新后的文档计数

当我使用 MySQL 时,update 方法通常会默认返回更新的数据计数,所以我想知道如何在 mongo 中获得相同的东西?

另外,使用 findAndModify 因为我希望该函数是多线程安全的。

请帮忙...

【问题讨论】:

    标签: java mongodb


    【解决方案1】:

    findAndModify 只更新一个文档,而在 MongoTemplate 中,我们有 updateMulti,它更新多个文档并返回一个 writeResult,它可以告诉您更新了多少文档

    /**
     * finds the elements based on query and modifies it
     * 
     * @param query
     * @param update
     * @param clazz
     * @return
     * @throws MeowException
     */
    protected <T> WriteResult modifyAll(final Query query, final Update update, final Class<T> clazz) throws MeowException{
        try{
            return getMongoTemplate().updateMulti(query, update, clazz);
        }catch(Exception ex){
            throw new MeowException(ex).withParam("query", query).withParam("update", update).withParam("class", clazz).logToFile("Exception in modifyAll");
        }
    }
    

    这可以称为

    WriteResult result = modifyAll(query, update, Kitten.class);
    logger.error("document updated count :"+result.getN());
    

    希望对你有帮助。

    【讨论】:

    • 我们是否必须实际获取所有这些记录的列表,甚至是所有更新记录的字段,而不是只获取计数?
    猜你喜欢
    • 2022-10-21
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    相关资源
    最近更新 更多