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

The following examples show how to use org.springframework.data.mongodb.core.query.Criteria. 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: mirrorgate   Source File: ReviewRepositoryImpl.java    License: Apache License 2.0 8 votes vote down vote up
@Override
public List<ApplicationDTO> getAverageRateByAppNamesAfterTimestamp(final List<String> names, final Long timestamp) {

    final Aggregation aggregation = newAggregation(
        match(Criteria.where("appname").in(names).and("timestamp").gte(timestamp)),
        group("appname", "platform")
            .first("appname").as("appname")
            .first("platform").as("platform")
            .count().as("votesShortTerm")
            .sum("starrating").as("ratingShortTerm")
    );

    //Convert the aggregation result into a List
    final AggregationResults<ApplicationDTO> groupResults
        = mongoTemplate.aggregate(aggregation, Review.class, ApplicationDTO.class);

    return groupResults.getMappedResults();
}
 
Example 2
Source Project: FEBS-Cloud   Source File: RouteLogServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
private Query getQuery(RouteLog routeLog) {
    Query query = new Query();
    Criteria criteria = new Criteria();
    if (StringUtils.isNotBlank(routeLog.getIp())) {
        criteria.and("ip").is(routeLog.getIp());
    }
    if (StringUtils.isNotBlank(routeLog.getTargetServer())) {
        criteria.and("targetServer").is(routeLog.getTargetServer());
    }
    if (StringUtils.isNotBlank(routeLog.getRequestMethod())) {
        criteria.and("requestMethod").is(routeLog.getRequestMethod().toUpperCase());
    }
    if (StringUtils.isNotBlank(routeLog.getCreateTimeFrom())
            && StringUtils.isNotBlank(routeLog.getCreateTimeTo())) {
        criteria.andOperator(
                Criteria.where("createTime").gt(routeLog.getCreateTimeFrom()),
                Criteria.where("createTime").lt(routeLog.getCreateTimeTo())
        );
    }
    query.addCriteria(criteria);
    return query;
}
 
Example 3
Source Project: biliob_backend   Source File: AuthorAchievementServiceImpl.java    License: MIT License 6 votes vote down vote up
/**
 * analyze author achievement
 *
 * @param mid author id
 * @return result
 */
@Override
@Async
public Result<?> analyzeAuthorAchievement(Long mid) {
    logger.info("为 {} 计算唯一成就", mid);
    List<Author.Achievement> achievements = mongoTemplate.find(Query.query(Criteria.where("author.mid").is(mid)).with(Sort.by("date").ascending()), Author.Achievement.class);
    HashSet<Integer> hashSet = new HashSet<>();
    achievements.forEach(a -> {
        hashSet.add(a.getCode());
    });
    Date lastDate = null;
    if (achievements.size() != 0) {
        lastDate = achievements.get(achievements.size() - 1).getDate();
    }
    Query q;
    if (lastDate == null) {
        q = Query.query(Criteria.where("mid").is(mid)).with(Sort.by("datetime").ascending());
    } else {
        q = Query.query(Criteria.where("mid").is(mid).and("datetime").gte(lastDate)).with(Sort.by("datetime").ascending());
    }
    List<Author.Data> dataList = mongoTemplate.find(q, Author.Data.class);
    doAddAchievements(mid, hashSet, dataList);
    return new Result<>(ResultEnum.SUCCEED);
}
 
Example 4
Source Project: biliob_backend   Source File: AdminServiceImpl.java    License: MIT License 6 votes vote down vote up
private void aggregateMatch(
        String matchField,
        String matchMethod,
        String matchValue,
        List<AggregationOperation> aggregationOperationsList) {
    String regex = "^[-+]?[\\d]*$";
    Pattern pattern = Pattern.compile(regex);
    if (!"".equals(matchField)) {
        if (Objects.equals(matchMethod, "is")) {
            if (pattern.matcher(matchValue).matches()) {
                aggregationOperationsList.add(
                        Aggregation.match(Criteria.where(matchField).is(Double.valueOf(matchValue))));
            }
            aggregationOperationsList.add(Aggregation.match(Criteria.where(matchField).is(matchValue)));
        } else if (Objects.equals(matchMethod, "gt")) {
            aggregationOperationsList.add(
                    Aggregation.match(Criteria.where(matchField).gt(Integer.valueOf(matchValue))));
        } else if (Objects.equals(matchMethod, "lt")) {
            aggregationOperationsList.add(
                    Aggregation.match(Criteria.where(matchField).lt(Integer.valueOf(matchValue))));
        }
    }
}
 
Example 5
Source Project: tutorials   Source File: DocumentQueryLiveTest.java    License: MIT License 6 votes vote down vote up
@Test
public void givenUsersExist_whenFindingUserWithNameEndWithC_thenUsersAreFound() {
    User user = new User();
    user.setName("Eric");
    user.setAge(45);
    mongoTemplate.insert(user);

    user = new User();
    user.setName("Antony");
    user.setAge(33);
    mongoTemplate.insert(user);

    user = new User();
    user.setName("Alice");
    user.setAge(35);
    mongoTemplate.insert(user);

    Query query = new Query();
    query.addCriteria(Criteria.where("name").regex("c$"));

    List<User> users = mongoTemplate.find(query, User.class);

    assertThat(users.size(), is(1));
}
 
Example 6
Source Project: eventeum   Source File: MongoEventStore.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Page<ContractEventDetails> getContractEventsForSignature(
        String eventSignature, String contractAddress, PageRequest pagination) {

    final Query query = new Query(
            Criteria.where("eventSpecificationSignature")
            .is(eventSignature)
            .and("address")
            .is(contractAddress))
        .with(new Sort(Direction.DESC, "blockNumber"))
        .collation(Collation.of("en").numericOrderingEnabled());

    final long totalResults = mongoTemplate.count(query, ContractEventDetails.class);

    //Set pagination on query
    query
        .skip(pagination.getPageNumber() * pagination.getPageSize())
        .limit(pagination.getPageSize());

    final List<ContractEventDetails> results = mongoTemplate.find(query, ContractEventDetails.class);

    return new PageImpl<>(results, pagination, totalResults);
}
 
Example 7
Source Project: scava   Source File: InternalValidator.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private Map<String, Float> readDistanceScores(String object) {
	Map<String, Float> result = new HashMap<String, Float>();
	Query query = new org.springframework.data.mongodb.core.query.Query();
	query.addCriteria(Criteria.where("type.name").is(_SIMILARITY_METHOD).orOperator(
			Criteria.where("fromArtifact.$id").is(new ObjectId(object)),
			Criteria.where("toArtifact.$id").is(new ObjectId(object))));
	DBCollection dbCollection = mongoTemplate.getCollection("relation");
	DBCursor cursor = dbCollection.find(query.getQueryObject());
	List<DBObject> list = cursor.toArray();
	for (DBObject dbObject : list) {
		String toArtifact = ((DBRef) dbObject.get("toArtifact")).getId().toString();
		String fromArtifact = ((DBRef) dbObject.get("fromArtifact")).getId().toString();
		double value = ((double) dbObject.get("value"));
		if (toArtifact.equals(object))
			result.put(fromArtifact, (float) (1 - value));
		else
			result.put(toArtifact, (float) (1 - value));
	}
	return result;
}
 
Example 8
Source Project: microcks   Source File: DailyStatisticRepositoryImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void incrementDailyStatistic(String day, String serviceName, String serviceVersion, String hourKey, String minuteKey){
   
   // Build a query to select specific object within collection.
   Query query = new Query(Criteria.where("day").is(day)
         .and("serviceName").is(serviceName)
         .and("serviceVersion").is(serviceVersion));
   
   // Other way to build a query using statically imported methods.
   //Query queryShort = query(where("day").is(day).and("serviceName").is(serviceName).and("serviceVersion").is(serviceVersion));
   
   // Build update to increment the 3 fields.
   Update update = new Update().inc("dailyCount", 1).inc("hourlyCount." + hourKey, 1).inc("minuteCount." + minuteKey, 1);
   
   // Do an upsert with find and modify.
   template.findAndModify(query, update, DailyStatistic.class);
}
 
Example 9
Source Project: secure-data-service   Source File: DenormalizerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    studentSectionAssociation.put("sectionId", SECTION1);
    studentSectionAssociation.put("studentId", STUDENT1);
    studentSectionAssociation.put("beginDate", BEGINDATE);
    studentSectionAssociation.put("endDate", ENDDATE1);

    WriteResult success = mock(WriteResult.class);
    CommandResult successCR = mock(CommandResult.class);
    CommandResult failCR = mock(CommandResult.class);
    when(success.getLastError()).thenReturn(successCR);
    when(successCR.ok()).thenReturn(true);
    when(successCR.get("value")).thenReturn("updated");
    when(failCR.get("value")).thenReturn(null);
    when(failCR.get("result")).thenReturn(null);
    when(studentCollection.update(any(DBObject.class), any(DBObject.class), eq(false), eq(true), eq(WriteConcern.SAFE))).thenReturn(
            success);
    when(studentCollection.update(any(DBObject.class), any(DBObject.class), eq(true), eq(true), eq(WriteConcern.SAFE))).thenReturn(
            success);
    when(template.getCollection("student")).thenReturn(studentCollection);

    Query query = new Query();
    query.addCriteria(Criteria.where("_id").is(SSAID));
    MongoEntity entity = new MongoEntity("studentSectionAssociation", studentSectionAssociation);
    when(template.findOne(eq(query), eq(Entity.class), eq("studentSectionAssociation"))).thenReturn(entity);
}
 
Example 10
Source Project: biliob_backend   Source File: SiteServiceImpl.java    License: MIT License 6 votes vote down vote up
@Override
public List<?> groupOnline(Integer days) {
    days = days > 365 ? 365 : days;
    Calendar c = Calendar.getInstance();
    c.add(Calendar.DATE, -days);
    return mongoTemplate.aggregate(
            Aggregation.newAggregation(
                    Aggregation.match(Criteria.where("datetime").gt(c.getTime())),
                    Aggregation.project()
                            .and("datetime").dateAsFormattedString("%Y-%m-%d").as("date")
                            .and("play_online").as("value")
                            .andExpression("week($datetime)").as("week"),
                    Aggregation.group("date")
                            .max("value").as("value").first("week").as("week"),
                    Aggregation.project("value", "week").and("_id").as("date"),
                    Aggregation.sort(Sort.Direction.ASC, "date"),
                    Aggregation.group("week")
                            .last("date").as("date")
                            .max("value").as("max")
                            .min("value").as("min")
                            .first("value").as("first")
                            .last("value").as("last")
            ), "site_info", StockData.class
    ).getMappedResults();
}
 
Example 11
/**
 * Filter for Data-related books in their title and output the title and authors.
 */
@Test
public void shouldRetrieveDataRelatedBooks() {

	Aggregation aggregation = newAggregation( //
			match(Criteria.where("volumeInfo.title").regex("data", "i")), //
			replaceRoot("volumeInfo"), //
			project("title", "authors"), //
			sort(Direction.ASC, "title"));

	AggregationResults<BookAndAuthors> result = operations.aggregate(aggregation, "books", BookAndAuthors.class);

	BookAndAuthors bookAndAuthors = result.getMappedResults().get(1);

	assertThat(bookAndAuthors.getTitle()).isEqualTo("Spring Data");
	assertThat(bookAndAuthors.getAuthors()).contains("Mark Pollack", "Oliver Gierke", "Thomas Risberg", "Jon Brisbin",
			"Michael Hunger");
}
 
Example 12
Source Project: iot-dc3   Source File: PointValueServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Page<PointValue> list(PointValueDto pointValueDto) {
    Criteria criteria = new Criteria();
    if (null == pointValueDto) {
        pointValueDto = new PointValueDto();
    }
    if (null != pointValueDto.getDeviceId()) {
        criteria.and("deviceId").is(pointValueDto.getDeviceId());
    }
    if (null != pointValueDto.getPointId()) {
        criteria.and("pointId").is(pointValueDto.getPointId());
    }
    if (null == pointValueDto.getPage()) {
        pointValueDto.setPage(new Pages());
    }
    Pages pages = pointValueDto.getPage();
    if (pages.getStartTime() > 0 && pages.getEndTime() > 0 && pages.getStartTime() <= pages.getEndTime()) {
        criteria.and("originTime").gte(pages.getStartTime()).lte(pages.getEndTime());
    }
    return queryPage(criteria, pointValueDto.getPage());
}
 
Example 13
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 14
protected Set<String> filterConnectedViaSection(Set<String> ids, Entity me) {
    if (ids.isEmpty()) {
        return ids;
    }
    //The fact that this goes through a subdoc on section means I can't reuse filterThroughSubdocs without adding another couple dozen parameters to that method...
    Set<String> sectionIds = getDenormIds(me, "section", "_id");
    if (sectionIds.isEmpty()) {
        return Collections.emptySet();
    }
    Query q = Query.query(Criteria.where("_id").in(sectionIds).and("teacherSectionAssociation").elemMatch(Criteria.where("body.teacherId").in(ids).andOperator(DateHelper.getExpiredCriteria())));
    q.fields().include("teacherSectionAssociation.$");
    Iterator<Entity> sections = getRepo().findEach(EntityNames.SECTION, q);
    Set<String> filtered = new HashSet<String>();
    while (sections.hasNext()) {
        Entity section = sections.next();
        List<Entity> tsas = section.getEmbeddedData().get("teacherSectionAssociation");
        if (tsas != null) {
            for (Entity tsa : tsas) {
                String teacher = (String) tsa.getBody().get("teacherId");
                filtered.add(teacher);
            }
        }
    }
    return filtered;
}
 
Example 15
Source Project: distributed-lock   Source File: SimpleMongoLock.java    License: MIT License 6 votes vote down vote up
@Override
protected boolean refresh(final String key, final String storeId, final String token, final long expiration) {
  final var updated = mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(key).and("token").is(token)),
    Update.update("expireAt", LocalDateTime.now().plus(expiration, ChronoUnit.MILLIS)),
    storeId);

  final var refreshed = updated.getModifiedCount() == 1;
  if (refreshed) {
    log.debug("Refresh query successfully affected 1 record for key {} with token {} in store {}", key, token, storeId);
  } else if (updated.getModifiedCount() > 0) {
    log.error("Unexpected result from refresh for key {} with token {} in store {}, released {}", key, token, storeId, updated);
  } else {
    log.warn("Refresh query did not affect any records for key {} with token {} in store {}. This is possible when refresh interval fires for the final time after the lock has been released",
      key, token, storeId);
  }

  return refreshed;
}
 
Example 16
Source Project: biliob_backend   Source File: UserAuthenticationProvider.java    License: MIT License 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) {
    String name = authentication.getPrincipal().toString();
    String password = authentication.getCredentials().toString();

    User user = UserUtils.getPasswdAndRole(name);
    String encodedPassword = new Md5Hash(password, user.getName()).toHex();
    if (encodedPassword.equals(user.getPassword())) {
        mongoTemplate.updateFirst(Query.query(
                new Criteria()
                        .orOperator(Criteria.where("name").is(name), Criteria.where("mail").is(name))),
                Update.update("password", bcryptPasswordEncoder.encode(password)), User.class);
        user.setPassword(bcryptPasswordEncoder.encode(password));
    }
    if (bcryptPasswordEncoder.matches(password, user.getPassword())) {
        Collection<GrantedAuthority> authorityCollection = new ArrayList<>();
        authorityCollection.add(new SimpleGrantedAuthority(user.getRole()));
        return new UsernamePasswordAuthenticationToken(name, password, authorityCollection);
    }
    throw new BadCredentialsException(ResultEnum.LOGIN_FAILED.getMsg());
}
 
Example 17
Source Project: chronus   Source File: EventMongoDBDaoImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<EventEntity> getLastEvent(String cluster, String address, String version) {
    Query query = new Query();
    query.addCriteria(Criteria.where("cluster").is(cluster));
    query.addCriteria(Criteria.where("address").is(address));
    query.addCriteria(Criteria.where("version").is(version));
    query.with(new Sort(Sort.Direction.DESC, "dateCreated"));
    query.limit(3);
    return super.selectList(query);
}
 
Example 18
Source Project: jstarcraft-core   Source File: MongoAccessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <K extends Comparable, T extends IdentityObject<K>> List<T> queryIntersection(Class<T> clazz, Map<String, Object> condition, StoragePagination pagination) {
	MongoMetadata metadata = metadatas.get(clazz);
	final Iterator<Entry<String, Object>> conditionIterator = condition.entrySet().iterator();
	Criteria criteria = Criteria.where(MongoMetadata.mongoId).exists(true);
	Criteria[] andCriterias = new Criteria[condition.size()];
	int index = 0;
	while (conditionIterator.hasNext()) {
		Entry<String, Object> keyValue = conditionIterator.next();
		String key = keyValue.getKey();
		Object value = keyValue.getValue();
		if (metadata.getPrimaryName().equals(key)) {
			key = MongoMetadata.mongoId;
		}
		andCriterias[index++] = Criteria.where(key).is(value);
	}
	Query query = Query.query(criteria.andOperator(andCriterias));
	if (pagination != null) {
		query.skip(pagination.getFirst());
		query.limit(pagination.getSize());
	}
	return template.find(query, clazz, metadata.getOrmName());
}
 
Example 19
Source Project: biliob_backend   Source File: TracerServiceImpl.java    License: MIT License 6 votes vote down vote up
private void getWeeklyCheckIn(Map<String, Object> resultMap) {
    resultMap.put(
            "weeklyCheckIn",
            mongoTemplate
                    .aggregate(
                            Aggregation.newAggregation(
                                    Aggregation.match(Criteria.where("message").is("签到")),
                                    Aggregation.project()
                                            .andExpression("week(_id)")
                                            .as("week")
                                            .andExpression("year(_id)")
                                            .as("year"),
                                    Aggregation.group("year", "week").count().as("count"),
                                    Aggregation.sort(Sort.by("year").ascending().and(Sort.by("week").ascending())),
                                    Aggregation.skip(1L),
                                    Aggregation.limit(10)),
                            "user_record",
                            Map.class)
                    .getMappedResults());
}
 
Example 20
Source Project: flow-platform-x   Source File: FlowUserDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<String> findAllFlowsByUserEmail(String email) {
    Query q = Query.query(Criteria.where("users").in(email));
    q.fields().exclude("users");

    List<FlowUsers> lists = mongoOps.find(q, FlowUsers.class);
    List<String> ids = new LinkedList<>();

    for (FlowUsers item : lists) {
        ids.add(item.getFlowId());
    }

    return ids;
}
 
Example 21
Source Project: biliob_backend   Source File: AuthorGroupServiceImpl.java    License: MIT License 5 votes vote down vote up
@Override
public Result<?> editAuthorList(String gid, String name, String desc, List<String> tagList) {
    ObjectId userId = UserUtils.getUserId();
    AuthorGroup ag = getAuthorList(gid);
    if (ag == null) {
        return new Result<>(ResultEnum.NOT_FOUND);
    }
    if (userId == null) {
        return new Result<>(ResultEnum.USER_NOT_EXIST);
    }
    if (hasPermission(userId, ag)) {
        mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(new ObjectId(gid))), Update.update("name", name).set("desc", desc).set("tagList", tagList), AuthorGroup.class);
    } else {
        return new Result<>(ResultEnum.PERMISSION_DENIED);
    }
    return new Result<>(ResultEnum.SUCCEED);
}
 
Example 22
Source Project: acelera-dev-brasil-2019-01   Source File: PersonService.java    License: Apache License 2.0 5 votes vote down vote up
public List<Person> buscar(Filtro filtro) {
        Query query = new Query();

//        if (filtro.isTemFoto()) {
//            query.addCriteria(Criteria.where("foto").ne(null));
//        } else {
//            query.addCriteria(Criteria.where("foto").is(null));
//        }

        query.addCriteria(Criteria.where("nome").is(filtro.getNome()));
        query.addCriteria(Criteria.where("altura").lte(filtro.getAltura()));
        return template.find(query, Person.class);
    }
 
Example 23
Source Project: beihu-boot   Source File: GridDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean delete(String gridId) {
    try {
        gridFsTemplate.delete(Query.query(Criteria.where("filename").is(gridId)));
        return true;
    } catch (Exception e) {
        return false;
    }
}
 
Example 24
Source Project: ic   Source File: EventServiceImpl.java    License: MIT License 5 votes vote down vote up
private void publishEvents(List<Event> sequentialEvents) {
    Preconditions.checkState(!sequentialEvents.isEmpty());
    //发布事件,先将事件hidden改为false,然后发qmq消息
    Long firstId = sequentialEvents.get(0).getId();
    Long lastId = sequentialEvents.get(sequentialEvents.size() - 1).getId();
    Query query = Query.query(Criteria.where("id").gte(firstId).lte(lastId));
    Update update = Update.update("_hidden", false);
    UpdateResult updateResult = mongoTemplate.updateMulti(query, update, Event.class);
    Preconditions.checkState(updateResult.wasAcknowledged());
    //getMatchedCount返回的是long,size返回的是int,不能使用equals
    Preconditions.checkState(updateResult.getMatchedCount() == sequentialEvents.size());
    //TODO
    logger.info("publishEvents定时任务发布了事件{}",
            sequentialEvents.stream().map(Event::getId).collect(Collectors.toList()));
}
 
Example 25
Source Project: biliob_backend   Source File: SpiderScheduler.java    License: MIT License 5 votes vote down vote up
@Async
private void keepMostViewVideoInterval() {
    Query q = Query.query(Criteria.where("cView").gt(5000000));
    q.fields().include("aid");
    List<Video> v = mongoTemplate.find(q, Video.class);
    for (Video video : v
    ) {
        Long aid = video.getAid();
        VideoIntervalRecord vir = mongoTemplate.findOne(Query.query(Criteria.where("aid").is(aid)), VideoIntervalRecord.class);
        if (vir == null || vir.getNext() == null || vir.getDate() == null) {
            mongoTemplate.upsert(Query.query(Criteria.where("aid").is(aid)), Update.update("interval", SECOND_OF_DAY).set("next", Calendar.getInstance().getTime()).set("date", Calendar.getInstance().getTime()), VideoIntervalRecord.class);
            logger.info("每日更新av{}", aid);
        }
    }
}
 
Example 26
Source Project: biliob_backend   Source File: AdminServiceImpl.java    License: MIT License 5 votes vote down vote up
@Override
@Async
public Result<?> reduceByMid(Long mid) {
    logger.info("正在精简 {} 的数据", mid);
    Calendar c = Calendar.getInstance();
    Calendar currentCalendar = Calendar.getInstance();
    currentCalendar.set(Calendar.YEAR, -1);
    c.set(Calendar.DATE, -1);
    while (currentCalendar.getTime().before(c.getTime())) {
        List<Author.Data> data = mongoTemplate.find(Query.query(Criteria.where("mid").is(mid).and("datetime").lt(c.getTime()).gt(currentCalendar.getTime())).with(Sort.by("datetime").ascending()).limit(100), Author.Data.class);
        if (data.size() < 50) {
            break;
        }
        Date lastDate = data.get(0).getDatetime();
        for (int i = 1; i < data.size(); i++) {
            Date currentDate = data.get(i).getDatetime();
            if (currentDate.getTime() - lastDate.getTime() < 1000 * 60 * 60 * 6) {
                mongoTemplate.remove(Query.query(Criteria.where("mid").is(mid).and("datetime").is(currentDate)), Author.Data.class);
            } else {
                lastDate = data.get(i).getDatetime();
            }
        }
        currentCalendar.setTime(data.get(data.size() - 1).getDatetime());
    }
    logger.info("精简 {} 的数据 完毕", mid);
    return new Result<>(ResultEnum.SUCCEED);
}
 
Example 27
Source Project: hmily   Source File: MongoCoordinatorRepository.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public HmilyTransaction findById(final String id) {
    Query query = new Query();
    query.addCriteria(new Criteria("transId").is(id));
    MongoAdapter cache = template.findOne(query, MongoAdapter.class, collectionName);
    return buildByCache(Objects.requireNonNull(cache));
}
 
Example 28
Source Project: Lottor   Source File: TxManagerServiceImpl.java    License: MIT License 5 votes vote down vote up
@Override
public List<TxTransactionItem> listTxItemByDelay(Long delay) {

    Timestamp current = new Timestamp(System.currentTimeMillis());
    Timestamp ddl = new Timestamp(current.getTime() - delay * 60 * 1000);
    DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String toStr = sdf.format(ddl);
    Criteria criteria = Criteria.where("createDate").lte(toStr).and("status").is(TransactionStatusEnum.PRE_COMMIT.getCode());
    Query query = Query.query(criteria);
    return mongoTemplate.find(query, TxTransactionItem.class, CollectionNameEnum.TxTransactionItem.name());
}
 
Example 29
Source Project: flow-platform-x   Source File: CustomSecretDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<Secret> listNameOnly(Secret.Category category) {
    Criteria criteria = Criteria.where("category").is(category);
    Query query = Query.query(criteria).with(SortByCreatedAtASC);
    query.fields().include("name");
    return operations.find(query, Secret.class);
}
 
Example 30
Source Project: maven-framework-project   Source File: UserDAOImpl.java    License: MIT License 5 votes vote down vote up
@Override
public User updateUser(User user) {
	Query query = new Query(new Criteria("id").is(user.getId()));
	
	Update update = new Update();
	update.set("userName", user.getUserName());
	update.set("password", user.getPassword());
	
	mongoTemplate.updateFirst(query, update, COLLECTION_NAME);
	
	return user;
}