MongoTemplate中findAndModify、findOneAndUpdate

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Fouse_/article/details/89396257

findAndModify、findOneAndUpdate分别是MongoTemplate和MongoCollection提供的事务级别的操作,最近是使用时发现每次都是返回更新之前的数据,认真查询Source Doc发现这两个方法都提供了多种重载函数

  • MongoCollection提供函数:
 	@Nullable
    TDocument findOneAndUpdate(Bson filter, Bson update);
     @Nullable
    TDocument findOneAndUpdate(Bson filter, Bson update, FindOneAndUpdateOptions options);
       @Nullable
    TDocument findOneAndUpdate(ClientSession clientSession, Bson filter, Bson update);
      @Nullable
    TDocument findOneAndUpdate(ClientSession clientSession, Bson filter, Bson update, FindOneAndUpdateOptions options);
  • MongoTemplate提供函数:
@Nullable
   @Override
   public <T> T findAndModify(Query query, Update update, Class<T> entityClass) {
   	return findAndModify(query, update, new FindAndModifyOptions(), entityClass,
   			operations.determineCollectionName(entityClass));
   }

   @Nullable
   @Override
   public <T> T findAndModify(Query query, Update update, Class<T> entityClass, String collectionName) {
   	return findAndModify(query, update, new FindAndModifyOptions(), entityClass, collectionName);
   }

   @Nullable
   @Override
   public <T> T findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> entityClass) {
   	return findAndModify(query, update, options, entityClass, operations.determineCollectionName(entityClass));
   }

   @Nullable
   @Override
   public <T> T findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> entityClass,
   		String collectionName) {

使用默认的函数都是传入的更新选项都是默认的new FindAndModifyOptions(),这也就不奇怪每次都返回原始的数据了
在这里插入图片描述
修改为返回更新后的数据:
在这里插入图片描述
mark一下

private boolean returnNew;//是否返回更新后的值
private boolean upsert;//如果不存在是否插入新的数据
private boolean remove;//是否删除该条数据

猜你喜欢

转载自blog.csdn.net/Fouse_/article/details/89396257
今日推荐