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

The following examples show how to use org.springframework.data.mongodb.core.query.Update. 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 File: PlatformDAO.java    From SI with 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 #2
Source File: UserServiceImpl.java    From biliob_backend with 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 #3
Source File: EventRepositoryMongoImpl.java    From konker-platform with 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 #4
Source File: CheckInCreditCalculator.java    From biliob_backend with 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 #5
Source File: PlatformDAO.java    From SI with 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 #6
Source File: ForceFocusCreditCalculator.java    From biliob_backend with 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 #7
Source File: MongoRecoverTransactionServiceImpl.java    From Raincat with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #8
Source File: MongoCompensationServiceImpl.java    From hmily with 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 #9
Source File: UserController.java    From spring-boot-examples with 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 #10
Source File: ProxyResourceDaoImpl.java    From ProxyPool with 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 #11
Source File: SequenceOption.java    From HA-DB with 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 #12
Source File: BaseItemServiceImpl.java    From Lottor with 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 #13
Source File: SpiderScheduler.java    From biliob_backend with MIT License 5 votes vote down vote up
public void updateVideoData() {
    Calendar c = Calendar.getInstance();
    List<Map> authorList = mongoTemplate.find(Query.query(Criteria.where("next").lt(c.getTime())), Map.class, "video_interval");
    for (Map freqData : authorList) {
        Long aid = (Long) freqData.get("aid");
        c.add(Calendar.SECOND, (Integer) freqData.get("interval"));
        mongoTemplate.updateFirst(Query.query(Criteria.where("mid").is(aid)), Update.update("next", c.getTime()), "video_interval");
        redisOps.postAuthorCrawlTask(aid);
    }
}
 
Example #14
Source File: VideoServiceImpl.java    From biliob_backend with MIT License 5 votes vote down vote up
private void upsertVideoFreq(Long aid, Integer interval) {
    Calendar nextCal = Calendar.getInstance();
    nextCal.add(Calendar.SECOND, interval);
    Date cTime = Calendar.getInstance().getTime();
    logger.debug("[UPSERT] 视频:{} 访问频率:{} 更新时间:{}", aid, interval, cTime);
    Update u = Update.update("date", cTime)
            .set("interval", interval);
    u.setOnInsert("next", nextCal.getTime());
    mongoTemplate.upsert(Query.query(Criteria.where("aid").is(aid)), u, "video_interval");
}
 
Example #15
Source File: CreditOperateHandle.java    From biliob_backend with MIT License 5 votes vote down vote up
private void updateUserInfo(Double credit, Double exp, String userName) {
    Query query = new Query(where("name").is(userName));
    Update update = new Update();
    update.set("credit", new BigDecimal(credit).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue());
    update.set("exp", new BigDecimal(exp).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue());
    mongoTemplate.updateFirst(query, update, User.class);
}
 
Example #16
Source File: SpiderScheduler.java    From biliob_backend with MIT License 5 votes vote down vote up
@Async
private void reduceIntervalByDaysAndInterval(Integer days, Integer interval) {
    Calendar c = Calendar.getInstance();
    c.add(Calendar.DATE, -days);
    mongoTemplate.updateMulti(Query.query(Criteria.where("date").lt(c.getTime()).and("interval").gt(interval)), Update.update("interval", interval), VideoIntervalRecord.class);
    logger.info("减少了 {}天前加入的 爬取频率到 {}", days, interval);
}
 
Example #17
Source File: CreditHandle.java    From biliob_backend with MIT License 5 votes vote down vote up
public ResponseEntity<Result<String>> modifyMail(User user, CreditConstant creditConstant, String newMail) {
    mongoTemplate.updateFirst(
            Query.query(Criteria.where("_id").is(user.getId())),
            Update.update("mail", newMail),
            "user");
    return getSuccessResponse(user, creditConstant, newMail);
}
 
Example #18
Source File: AbstractCreditCalculator.java    From biliob_backend with MIT License 5 votes vote down vote up
void setExecuted(ObjectId objectId) {
    // 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");
}
 
Example #19
Source File: FlowUserDaoImpl.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
@Override
public void remove(String flowId, Set<String> userIds) {
    Query q = Query.query(Criteria.where("_id").is(flowId));

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

    mongoOps.updateFirst(q, u, FlowUsers.class);
}
 
Example #20
Source File: SimpleMongoLock.java    From distributed-lock with MIT License 5 votes vote down vote up
@Override
protected String acquire(final String key, final String storeId, final String token, final long expiration) {
  final var query = Query.query(Criteria.where("_id").is(key));
  final var update = new Update()
    .setOnInsert("_id", key)
    .setOnInsert("expireAt", LocalDateTime.now().plus(expiration, ChronoUnit.MILLIS))
    .setOnInsert("token", token);

  final var options = new FindAndModifyOptions().upsert(true).returnNew(true);
  final var doc = mongoTemplate.findAndModify(query, update, options, LockDocument.class, storeId);

  final var locked = doc.getToken().equals(token);
  log.debug("Tried to acquire lock for key {} with token {} in store {}. Locked: {}", key, token, storeId, locked);
  return locked ? token : null;
}
 
Example #21
Source File: UserServiceImpl.java    From biliob_backend with MIT License 5 votes vote down vote up
@Override
public ResponseEntity<?> refreshVideo(@Valid String bvid) {
    User u = UserUtils.getUser();
    UserRecord userRecord = mongoTemplate.insert(new UserRecord(CreditConstant.REFRESH_VIDEO_DATA, bvid, u.getName()));
    Result<?> result = creditOperateHandle.doAsyncCreditOperate(u, CreditConstant.REFRESH_VIDEO_DATA,
            () -> mongoTemplate.updateFirst(Query.query(Criteria.where("bvid").is(bvid)),
                    new Update().addToSet("order", userRecord.getId()), "video_interval"));
    return ResponseEntity.ok(result);
}
 
Example #22
Source File: CustomJobNumberDaoImpl.java    From flow-platform-x with 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 #23
Source File: TestMongoXMLConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpsert() {
    final Query query = new Query(
            Criteria.where("title").is("To Ill a Mocking Bird")
                    .and("author.firstName").is("Bob")
                    .and("author.lastName").is("Smith"));

    final Update update = Update.update("pageCount", 1);
    mongoOperations.upsert(query, update, Book.class);
    // Calling update using query: { "title" : "To Ill a Mocking Bird" , "author.firstName" : "Bob" , "author.lastName" : "Smith"} and update: { "$set" : { "pageCount" : 1}} in collection: book
}
 
Example #24
Source File: MongoTestDao.java    From SpringBootLearn with 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 #25
Source File: ProxyDaoImpl.java    From ProxyPool with Apache License 2.0 5 votes vote down vote up
@Override
public boolean updateProxyById(String id) {

    Query query = new Query(Criteria.where("id").is(id));
    Update update = new Update();
    update.set("lastSuccessfulTime", new Date().getTime());        //最近一次验证成功的时间
    WriteResult writeResult = mongoTemplate.updateFirst(query, update, ProxyData.class,Constant.COL_NAME_PROXY);
    return writeResult!=null && writeResult.getN() > 0;
}
 
Example #26
Source File: TestMongoJavaConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpsert() {
    final Query query = new Query(
            Criteria.where("title").is("To Ill a Mocking Bird")
                    .and("author.firstName").is("Bob")
                    .and("author.lastName").is("Smith"));

    final Update update = Update.update("pageCount", 1);
    mongoOperations.upsert(query, update, Book.class);
    // Calling update using query: { "title" : "To Ill a Mocking Bird" , "author.firstName" : "Bob" , "author.lastName" : "Smith"} and update: { "$set" : { "pageCount" : 1}} in collection: book
}
 
Example #27
Source File: MongoPersister.java    From statefulj with Apache License 2.0 5 votes vote down vote up
protected Update buildUpdate(State<T> current, State<T> next) {
	Update update = new Update();
	update.set("prevState", current.getName());
	update.set("state", next.getName());
	update.set("updated", Calendar.getInstance().getTime());
	return update;
}
 
Example #28
Source File: AdminServiceImpl.java    From biliob_backend with 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);
}
 
Example #29
Source File: HmlHandler.java    From -Data-Stream-Development-with-Apache-Spark-Kafka-and-Spring-Boot with MIT License 5 votes vote down vote up
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 File: DbRoutineOperate.java    From ClusterDeviceControlPlatform with MIT License 5 votes vote down vote up
/**
     * 更新员工的考勤表
     *
     * @param employeeObjectId 员工的 ObjectId,该值不能为 Null
     * @param chargeStatus     设备状态包
     */
    public void updateRoutineById(String employeeObjectId, MsgReplyDeviceStatus chargeStatus, MsgReplyDeviceStatus.Type type) {

        Query query = new Query(Criteria.where("_id").is(new ObjectId(employeeObjectId)));

        HistoryInfo historyInfo = new HistoryInfo(chargeStatus.getTime(), chargeStatus.getStatus());
        Update update;

        switch (type) {
            case WORK:
                update = new Update().push("WorkStatus", historyInfo);
                break;
            case CHARGE:
                update = new Update().push("ChargeStatus", historyInfo);
                break;
            default:
                return;
        }
        operations.upsert(query, update, LampStatusHistory.class);
//        Optional<LampStatusHistory> optional = repository.findById(employeeObjectId);
//        LampStatusHistory document = optional.orElseGet(() -> {
//            LampStatusHistory temp = new LampStatusHistory();
//            temp.setId(employeeObjectId);
//            return temp;
//        });
//        switch (type) {
//            case WORK:
//                document.getWorkStatus().add(new HistoryInfo(chargeStatus.getTime(), chargeStatus.getStatus()));
//                break;
//            case CHARGE:
//                document.getChargeStatus().add(new HistoryInfo(chargeStatus.getTime(), chargeStatus.getStatus()));
//                break;
//            default:
//        }
//        repository.save(document);
    }