Java Code Examples for org.springframework.data.mongodb.core.query.Update

The following examples show how to use org.springframework.data.mongodb.core.query.Update. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: konker-platform   Source File: EventRepositoryMongoImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Remove events from device in logical way
 * @param tenant
 * @param application
 * @param deviceGuid
 * @param type
 * @throws Exception
 */
protected void doRemoveBy(Tenant tenant, Application application, String deviceGuid, Type type) throws Exception {

    List<Criteria> criterias = new ArrayList<>();

    criterias.add(
            Criteria.where(MessageFormat.format("{0}.{1}", type.getActorFieldName(),"deviceGuid"))
                    .is(deviceGuid)
    );
    Query query = Query.query(
            Criteria.where(
                    MessageFormat.format("{0}.{1}", type.getActorFieldName(),"tenantDomain")
            ).is(tenant.getDomainName())
                    .andOperator(criterias.toArray(new Criteria[criterias.size()])));

    Update update = new Update();
    update.set("deleted", true);
    mongoTemplate.updateMulti(query, update, DBObject.class, type.getCollectionName());
}
 
Example 2
Source Project: SI   Source File: PlatformDAO.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public PlatformVO updatePlatform(PlatformVO vo) {
    Query query = new Query(new Criteria("id").is(vo.getId()));
	
	Update update = new Update();
	update.set("spId", vo.getSpId());
	update.set("serverName", vo.getServerName());
	update.set("serverHost", vo.getServerHost());
	update.set("serverPort", vo.getServerPort());
	update.set("protocol", vo.getProtocol());
	update.set("cseId", vo.getCseId());
	update.set("cseName", vo.getCseName());
	update.set("maxTps", vo.getMaxTps());
	update.set("updateTime", DateTimeUtil.getDateTimeByPattern("yyyy/MM/dd HH:mm:ss"));
	
	mongoTemplate.updateFirst(query, update, COLLECTION_NAME);
	
	return vo;
}
 
Example 3
Source Project: spring-boot-examples   Source File: UserController.java    License: Apache License 2.0 6 votes vote down vote up
@PostMapping(value = "")
public JsonResult add(User user) {
    String msg = verifySaveForm(user);
    if (!StringUtils.isEmpty(msg)) {
        return new JsonResult(false, msg);
    }

    if (user.getId() == null) {
        user.setCreateTime(new Date());
        user.setLastUpdateTime(new Date());
        User newUser = mongoTemplate.insert(user, "user");
        return new JsonResult(true, newUser);
    } else {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(user.getId()));

        Update update = new Update();
        update.set("name", user.getName());
        update.set("password", user.getPassword());
        update.set("address", user.getAddress());
        update.set("last_update_time", new Date());

        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, "user");
        return new JsonResult(true, updateResult);
    }
}
 
Example 4
Source Project: ProxyPool   Source File: ProxyResourceDaoImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean saveResourcePlan(ResourcePlan resourcePlan) {
    boolean result = false;
    if(resourcePlan.getAddTime() == 0) { //insert
        resourcePlan.setAddTime(new Date().getTime());
        resourcePlan.setModTime(new Date().getTime());

        mongoTemplate.save(resourcePlan, Constant.COL_NAME_RESOURCE_PLAN);
        result = Preconditions.isNotBlank(resourcePlan.getId());

    } else {                            //update
        Query query = new Query().addCriteria(Criteria.where("_id").is(resourcePlan.getId()));
        Update update = new Update();
        update.set("startPageNum", resourcePlan.getStartPageNum());
        update.set("endPageNum", resourcePlan.getEndPageNum());
        update.set("modTime", new Date().getTime());

        WriteResult writeResult = mongoTemplate.updateFirst(query, update, Constant.COL_NAME_RESOURCE_PLAN);
        result = writeResult!=null && writeResult.getN() > 0;
    }

    return result;
}
 
Example 5
Source Project: HA-DB   Source File: SequenceOption.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private long generate(MongoTemplate template, String collectionName, String rowName, Long incrementVal) {
	Criteria criteria = Criteria.where(SequenceId.COLLNAME).is(collectionName);
	if (rowName != null) {
		criteria.and(SequenceId.ROW).is(rowName);
	} else {
		criteria.and(SequenceId.ROW).ne("").ne(null);
	}
	Query query = new Query(criteria);

	Update update = new Update();
	update.inc(SequenceId.SEQ, incrementVal);
	FindAndModifyOptions options = new FindAndModifyOptions();
	options.upsert(false); // 不做插入,所有的自增键由表维护
	options.returnNew(true);
	SequenceId seqId = template.findAndModify(query, update, options, SequenceId.class,
			SequenceId.SEQUENCE_ID_COL_NAME);

	return seqId.getSeq();
}
 
Example 6
Source Project: SI   Source File: PlatformDAO.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public PlatformVO updatePlatform(PlatformVO vo) {
    Query query = new Query(new Criteria("id").is(vo.getId()));
	
	Update update = new Update();
	update.set("spId", vo.getSpId());
	update.set("serverName", vo.getServerName());
	update.set("serverHost", vo.getServerHost());
	update.set("serverPort", vo.getServerPort());
	update.set("protocol", vo.getProtocol());
	update.set("cseId", vo.getCseId());
	update.set("cseName", vo.getCseName());
	update.set("maxTps", vo.getMaxTps());
	update.set("updateTime", DateTimeUtil.getDateTimeByPattern("yyyy/MM/dd HH:mm:ss"));
	
	mongoTemplate.updateFirst(query, update, COLLECTION_NAME);
	
	return vo;
}
 
Example 7
Source Project: secure-data-service   Source File: CommandProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private void dumpMongoTrackingStats(String batchId) throws UnknownHostException {
    Map<String, ? extends Map<String, Pair<AtomicLong, AtomicLong>>> stats = Aspects.aspectOf(MongoTrackingAspect.class).getStats();

    if (stats != null) {
        String hostName = InetAddress.getLocalHost().getHostName();
        hostName = hostName.replaceAll("\\.", "#");
        Update update = new Update();
        update.set("executionStats." + hostName, stats);

        LOG.info("Dumping runtime stats to db for job {}", batchId);
        LOG.info(stats.toString());

        // TODO: move to BatchJobDAO
        mongo.updateFirst(new Query(Criteria.where(BATCH_JOB_ID).is(batchId)), update, "newBatchJob");
        Aspects.aspectOf(MongoTrackingAspect.class).reset();
    }
}
 
Example 8
Source Project: Lottor   Source File: BaseItemServiceImpl.java    License: MIT License 6 votes vote down vote up
@Override
public int updateItem(BaseItem baseItem) {
    Query query = new Query();
    query.addCriteria(new Criteria("type").is(baseItem.getType()).and("itemId").is(baseItem.getItemId()));
    BaseItem item = mongoTemplate.findOne(query, BaseItem.class, CollectionNameEnum.BaseItem.name());
    if (Objects.isNull(item)) {
        baseItem.setHealthyState(false);
        baseItem.setRetryCount(1);
        baseItem.setLastModified(System.currentTimeMillis());
        mongoTemplate.save(baseItem, collectionName);
        return baseItem.getRetryCount();
    }
    int count = item.getRetryCount();
    Update update = Update.update("retryCount", count + 1);
    update.set("lastModified", System.currentTimeMillis());
    if (count < 1) {
        update.set("healthyState", false);
    }
    mongoTemplate.updateFirst(query, update, BaseItem.class, collectionName);
    return count + 1;
}
 
Example 9
Source Project: hmily   Source File: MongoCompensationServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Boolean updateRetry(final String id, final Integer retry, final String appName) {
    if (StringUtils.isBlank(id) || StringUtils.isBlank(appName) || Objects.isNull(retry)) {
        return Boolean.FALSE;
    }
    final String mongoTableName = RepositoryPathUtils.buildMongoTableName(appName);
    Query query = new Query();
    query.addCriteria(new Criteria("transId").is(id));
    Update update = new Update();
    update.set("lastTime", DateUtils.getCurrentDateTime());
    update.set("retriedCount", retry);
    final UpdateResult updateResult = mongoTemplate.updateFirst(query, update,
            MongoAdapter.class, mongoTableName);
    if (updateResult.getModifiedCount() <= 0) {
        throw new HmilyRuntimeException("更新数据异常!");
    }
    return Boolean.TRUE;
}
 
Example 10
@Override
public Boolean updateRetry(final String id, final Integer retry, final String applicationName) {
    if (StringUtils.isBlank(id)
            || StringUtils.isBlank(applicationName)
            || Objects.isNull(retry)) {
        return Boolean.FALSE;
    }
    final String mongoTableName = RepositoryPathUtils.buildMongoTableName(applicationName);

    Query query = new Query();
    query.addCriteria(new Criteria("transId").is(id));
    Update update = new Update();
    update.set("lastTime", DateUtils.getCurrentDateTime());
    update.set("retriedCount", retry);
    final WriteResult writeResult = mongoTemplate.updateFirst(query, update,
            MongoAdapter.class, mongoTableName);
    if (writeResult.getN() <= 0) {
        throw new TransactionRuntimeException("更新数据异常!");
    }
    return Boolean.TRUE;
}
 
Example 11
Source Project: biliob_backend   Source File: ForceFocusCreditCalculator.java    License: MIT License 6 votes vote down vote up
public void upsertAuthorFreq(Long mid, Integer interval) {
    AuthorIntervalRecord preInterval =
            mongoTemplate.findOne(Query.query(Criteria.where("mid").is(mid)),
                    AuthorIntervalRecord.class, "author_interval");
    Calendar nextCal = Calendar.getInstance();
    Date cTime = Calendar.getInstance().getTime();
    nextCal.add(Calendar.SECOND, interval);
    // 更新访问频率数据。

    Update u = Update.update("date", cTime).set("interval", interval);
    // 如果此前没有访问频率数据,或者更新后的访问时间比原来的访问时间还短,则刷新下次访问的时间。
    if (preInterval == null
            || nextCal.getTimeInMillis() < preInterval.getNext().getTime()) {
        u.set("next", nextCal.getTime());
    }
    mongoTemplate.upsert(Query.query(Criteria.where("mid").is(mid)), u, "author_interval");
}
 
Example 12
Source Project: biliob_backend   Source File: CheckInCreditCalculator.java    License: MIT License 6 votes vote down vote up
@Override
public ResponseEntity execute(User user, ObjectId objectId) {
    Boolean isCheckedIn =
            mongoTemplate.exists(new Query(where("name").is(user.getName())), "check_in");
    String userName = user.getName();
    Double credit = user.getCredit();
    if (isCheckedIn) {
        throw new BusinessException(ExceptionEnum.ALREADY_SIGNED);
    } else {
        // 插入已签到集合
        mongoTemplate.insert(new CheckIn(userName), "check_in");

        // update execute status
        Query query = new Query(where("_id").is(objectId));
        Update update = new Update();
        update.set("isExecuted", true);
        mongoTemplate.updateFirst(query, update, "user_record");
    }
    return null;
}
 
Example 13
Source Project: biliob_backend   Source File: UserServiceImpl.java    License: MIT License 6 votes vote down vote up
/**
 * Refresh author data immediately.
 *
 * @param mid author id
 * @return response
 */
@Override
public ResponseEntity<?> refreshAuthor(@Valid Long mid) {
    User u = UserUtils.getUser();
    UserRecord userRecord = mongoTemplate.insert(new UserRecord(CreditConstant.REFRESH_AUTHOR_DATA, String.valueOf(mid), u.getName()));
    Result<?> result = creditOperateHandle.doAsyncCreditOperate(u, CreditConstant.REFRESH_AUTHOR_DATA,
            () -> {
                Query q = Query.query(Criteria.where("mid").is(mid));
                if (!mongoTemplate.exists(q, AuthorIntervalRecord.class)) {
                    authorService.upsertAuthorFreq(mid, 86400);
                }
                return mongoTemplate.updateFirst(q,
                        new Update().addToSet("order", userRecord.getId()), AuthorIntervalRecord.class);
            });
    return ResponseEntity.ok(result);
}
 
Example 14
Source Project: SpringBootLearn   Source File: MongoTestDao.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 更新对象
 */
public void updateTest(MongoTest test) {
    Query query = new Query(Criteria.where("id").is(test.getId()));
    Update update = new Update().set("age", test.getAge()).set("name", test.getName());
    //更新查询返回结果集的第一条
    mongoTemplate.updateFirst(query, update, MongoTest.class);
    //更新查询返回结果集的所有
    // mongoTemplate.updateMulti(query,update,TestEntity.class);
}
 
Example 15
Source Project: Dodder   Source File: TorrentDaoImpl.java    License: MIT License 5 votes vote down vote up
@Override
public void upsert(Torrent torrent) {
	Query query = Query.query(Criteria.where("infoHash").is(torrent.getInfoHash()));
	Update update = new Update().addToSet("createDate", torrent.getCreateDate())
			.addToSet("fileName", torrent.getFileName())
			.addToSet("files", torrent.getFiles())
			.addToSet("fileSize", torrent.getFileSize())
			.addToSet("fileType", torrent.getFileType());
	mongoTemplate.upsert(query, update, Torrent.class);
}
 
Example 16
Source Project: fw-spring-cloud   Source File: SysUserServiceTenantTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 更新多条
 */
@Test
public void updateMutTest(){
    Query query = Query.query(Criteria.where("tenant_code").is(null));
    Update update = Update.update("tenant_code", "XYS");
    UpdateResult updateResult = mongoTemplate.updateMulti(query, update, SysUser.class);
    log.info("update 影响行数:"+updateResult.getModifiedCount());
}
 
Example 17
Source Project: fw-spring-cloud   Source File: SysUserServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * 更新
     */
    @Test
    public void updateTest(){
        Query query = Query.query(Criteria.where("user_phone").is("50"));
        Update update = Update.update("pos_code", "XYS11023");
//        Update update = Update.update("user_phone", "55").set("pos_code", "XYS11023");
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, SysUser.class);
        log.info("update 影响行数:"+updateResult.getModifiedCount());
    }
 
Example 18
Source Project: flow-platform-x   Source File: FlowUserDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void remove(String flowId, Set<String> emails) {
    Query q = Query.query(Criteria.where("_id").is(flowId));

    Update u = new Update();
    u.pullAll("users", emails.toArray());

    mongoOps.updateFirst(q, u, FlowUsers.class);
}
 
Example 19
Source Project: chronus   Source File: EventMongoDBDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void updateDuplicateEvent(EventEntity eventEntity, Object lastId) {
    Query query = new Query();
    query.addCriteria(Criteria.where("address").is(eventEntity.getAddress()));
    query.addCriteria(Criteria.where("cluster").is(eventEntity.getCluster()));
    query.addCriteria(Criteria.where("version").is(eventEntity.getVersion()));

    Update update = new Update();
    update.set("message", eventEntity.getMessage());
    update.set("content", eventEntity.getContent());
    update.set("costTime", eventEntity.getCostTime());
    update.set("dateCreated", eventEntity.getDateCreated());
    super.updateById(lastId, update);
}
 
Example 20
Source Project: hmily   Source File: MongoCoordinatorRepository.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int updateStatus(final String id, final Integer status) {
    Query query = new Query();
    query.addCriteria(new Criteria("transId").is(id));
    Update update = new Update();
    update.set("status", status);
    final UpdateResult updateResult = template.updateFirst(query, update, MongoAdapter.class, collectionName);
    if (updateResult.getModifiedCount() <= 0) {
        throw new HmilyRuntimeException("update data exception!");
    }
    return ROWS;
}
 
Example 21
Source Project: flow-platform-x   Source File: CustomJobNumberDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JobNumber increaseBuildNumber(String flowId) {
    return operations.findAndModify(
            query(where("_id").is(flowId)),
            new Update().inc("number", 1),
            options().returnNew(true).upsert(true),
            JobNumber.class);
}
 
Example 22
Source Project: secure-data-service   Source File: MongoEntityRepository.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@MigrateEntity
public Entity findAndUpdate(String collectionName, NeutralQuery neutralQuery, Update update) {
    Query query = this.getQueryConverter().convert(collectionName, neutralQuery);
    FindAndModifyOptions options = new FindAndModifyOptions();
    Entity result = template.findAndModify(query, update, options, getRecordClass(), collectionName);

    if (result != null
            && collectionName.equals(EntityNames.EDUCATION_ORGANIZATION)) {
        updateAllSchoolLineage();
    }

    return result;
}
 
Example 23
Source Project: sanshanblog   Source File: UserRepositoryImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public WriteResult changeUserInfo(UserDO userDO) {
    Query query = new Query();
    query.addCriteria(new Criteria("username").is(userDO.getUsername()));
    Update update = new Update();
    if (userDO.getBlogLink()!=null){
        update.set("blogLink", userDO.getBlogLink());
    }
    if (userDO.getAvatar()!=null){
        update.set("avatar", userDO.getAvatar());
    }
    return this.mongoTemplate.upsert(query, update, UserDO.class);
}
 
Example 24
Source Project: biliob_backend   Source File: AuthorGroupServiceImpl.java    License: MIT License 5 votes vote down vote up
@Override
public Result<UpdateResult> setAuthorListInfo(String id, String name, String desc, List<String> tag) {
    return creditOperateHandle.doCreditOperate(
            UserUtils.getUser(), CreditConstant.MODIFY_AUTHOR_LIST_INFO, id, () ->
                    mongoTemplate.updateFirst(
                            Query.query(Criteria.where("_id").is(id)),
                            Update.update("name", name).currentDate("updateTime").set("desc", desc).set("tag", tag),
                            AuthorGroup.class));
}
 
Example 25
Source Project: AppStash   Source File: UserItemPreferenceUpdateListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onAfterSave(Order order, DBObject dbo) {
    ObjectId userId = order.getUserId();
    for (OrderItem item : order.getOrderItems()) {
        String articleId = item.getProduct().getArticleId();

        Criteria criteria = Criteria.where("userId").is(userId)
                .and("articleId").is(articleId);
        Update update = Update.update("created_at", new Date()).inc("preference", 1);

        mongoOperations.upsert(Query.query(criteria), update, UserItemPreference.class);
    }
}
 
Example 26
Source Project: Almost-Famous   Source File: SchoolDaoImpl.java    License: MIT License 5 votes vote down vote up
public boolean upSchool(School school) {
    Query query = new Query().addCriteria(Criteria.where("rid").is(school.getRid()));
    Update update = new Update()
            .set("schools", school.getSchools());
    gameMongoTemplate.findAndModify(query, update, getEntityClass());
    return true;
}
 
Example 27
Source Project: Almost-Famous   Source File: ActorBagDaoImpl.java    License: MIT License 5 votes vote down vote up
@Override
public void updateActorBag(ActorBag pack) {
    Query query = new Query(Criteria.where("rid").is(pack.getRid()));
    Update update = new Update()
            .set("packages", pack.getPackages())
            .set("buyCount", pack.getBuyCount())
            .set("selectCount", pack.getSelectCount())
            .set("probability", pack.getProbability());
    gameMongoTemplate.findAndModify(query, update, getEntityClass());
}
 
Example 28
Source Project: secure-data-service   Source File: TenantMongoDA.java    License: Apache License 2.0 5 votes vote down vote up
private boolean markPreloadStarted(Entity tenant) {
    return entityRepository.doUpdate(
            TENANT_COLLECTION,
            new NeutralQuery().addCriteria(new NeutralCriteria("_id", "=", tenant.getEntityId())).addCriteria(
                    PRELOAD_READY_CRITERIA),
            Update.update("body." + TenantMongoDA.LANDING_ZONE + ".$." + TenantMongoDA.PRELOAD_DATA + "."
                    + TenantMongoDA.PRELOAD_STATUS, "started"));

}
 
Example 29
private void updateRsvp(RsvpDocument rsvp) {
    mongoTemplate.updateFirst(
            new Query().addCriteria(Criteria.where("id").is(rsvp.getId())),
            new Update().set("status", RsvpStatus.FAILED), RsvpDocument.class)
            .retry(RETRIES)
            .subscribe();
}
 
Example 30
Source Project: biliob_backend   Source File: AdminServiceImpl.java    License: MIT License 5 votes vote down vote up
/**
 * 取消管理员权限
 *
 * @param userName 用户名
 * @return 处理反馈
 */
@Override
public ResponseEntity cancelUserAdminRole(@Valid String userName) {
    mongoTemplate.updateFirst(
            Query.query(Criteria.where("name").is(userName)), Update.update("role", "普通研究员"), "user");
    return new ResponseEntity<>(new Result(ResultEnum.SUCCEED), HttpStatus.OK);
}