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

The following examples show how to use org.springframework.data.mongodb.core.query.Criteria. 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: ReviewRepositoryImpl.java    From mirrorgate with 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 File: RouteLogServiceImpl.java    From FEBS-Cloud with Apache License 2.0 7 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 File: SiteServiceImpl.java    From biliob_backend with 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 #4
Source File: EventMongoDBDaoImpl.java    From chronus with 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 #5
Source File: DocumentQueryLiveTest.java    From tutorials with 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 File: TransitiveStudentToStaffValidator.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: AdminServiceImpl.java    From biliob_backend with 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 #8
Source File: MongoEventStore.java    From eventeum with 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 #9
Source File: MongoAccessor.java    From jstarcraft-core with 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 #10
Source File: AuthorAchievementServiceImpl.java    From biliob_backend with 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 #11
Source File: InternalValidator.java    From scava with 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 #12
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 #13
Source File: PointValueServiceImpl.java    From iot-dc3 with 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 #14
Source File: DailyStatisticRepositoryImpl.java    From microcks with 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 #15
Source File: SpringBooksIntegrationTests.java    From spring-data-examples with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #16
Source File: DenormalizerTest.java    From secure-data-service with 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 #17
Source File: TracerServiceImpl.java    From biliob_backend with 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 #18
Source File: UserAuthenticationProvider.java    From biliob_backend with 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 #19
Source File: SimpleMongoLock.java    From distributed-lock with 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 #20
Source File: MongoDBArtifactStore.java    From hawkbit-extensions with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void deleteBySha1(final String tenant, final String sha1Hash) {
    try {
        deleteArtifact(gridFs.findOne(new Query()
                .addCriteria(Criteria.where(FILENAME).is(sha1Hash).and(TENANT_QUERY).is(sanitizeTenant(tenant)))));
    } catch (final MongoException e) {
        throw new ArtifactStoreException(e.getMessage(), e);
    }
}
 
Example #21
Source File: TaskMongoDBDaoImpl.java    From chronus with Apache License 2.0 5 votes vote down vote up
@Override
public TaskEntity selectTaskInfoByTaskName(String cluster, String taskName) {
    Query query = new Query();
    query.addCriteria(Criteria.where("cluster").is(cluster));
    query.addCriteria(Criteria.where("taskName").is(taskName));
    return selectOne(query);
}
 
Example #22
Source File: ClusterManager.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Cluster getClusterByArtifactsIdAndClusterizationId(String artifactId, String clusterizationId) {
	Query q1 = new Query();
	q1.addCriteria(Criteria.where("clusterization.$id").is(new ObjectId(clusterizationId)).orOperator(
			Criteria.where("artifacts._id").is(new ObjectId(artifactId)),
			Criteria.where("mostRepresentative._id").is(new ObjectId(artifactId))));
			
	Cluster result = mongoOperations.findOne(q1, Cluster.class);
	
	return result;
}
 
Example #23
Source File: DamnYouServiceImpl.java    From biliob_backend with MIT License 5 votes vote down vote up
public void saveHistoryDataFromTxt(BufferedReader br) throws IOException {
    logger.info("发动番剧历史数据更新");
    String line;
    Calendar c = Calendar.getInstance();
    while ((line = br.readLine()) != null) {
        try {
            String[] params = line.split("\t", -1);
            c.setTimeInMillis(Long.parseLong(params[10]));
            Long sid = Long.valueOf(params[0]);
            BangumiData bangumiData = new BangumiData(
                    sid,
                    Long.valueOf(params[1]),
                    Long.valueOf(params[2]),
                    Long.valueOf(params[3]),
                    Integer.valueOf(params[4]),
                    Integer.valueOf(params[5]),
                    Integer.valueOf(params[6]),
                    Integer.valueOf(params[7]),
                    Float.valueOf(params[8]),
                    Integer.valueOf(params[9]),
                    c.getTime()
            );
            if (!mongoTemplate.exists(Query.query(Criteria.where("sid").is(sid).and("datetime").is(c.getTime())), BangumiData.class)) {
                mongoTemplate.save(bangumiData);
            }
        } catch (Exception e) {
            logger.error(line);
            e.printStackTrace();
        }
    }
}
 
Example #24
Source File: ConferenceRepositoryImpl.java    From spring4-sandbox with Apache License 2.0 5 votes vote down vote up
@Override
public void updateConferenceDescription(String description, String id) {
	WriteResult result = mongoTemplate.updateMulti(
			Query.query(Criteria.where("id").is(id)),
			Update.update("description", description), Conference.class);
	
	log.debug("result @"+result.getN());
}
 
Example #25
Source File: EventServiceImpl.java    From ic with MIT License 5 votes vote down vote up
private Long getLastNotHiddenEventId() {
    //因为_hidden可能为null,所以使用ne(true)
    Query query = new Query(Criteria.where("_hidden").ne(true));
    query.with(Sort.by(Sort.Order.desc("id"))).limit(1); //按id进行 降序
    Event event = mongoTemplate.findOne(query, Event.class);
    if (event != null) {
        return event.getId();
    } else {
        return 0L;
    }
}
 
Example #26
Source File: DataTablesRepositoryImpl.java    From spring-data-mongodb-datatables with Apache License 2.0 5 votes vote down vote up
@Override
public <R> DataTablesOutput<R> findAll(DataTablesInput input, Criteria additionalCriteria, Criteria preFilteringCriteria, Function<T, R> converter) {
    DataTablesOutput<R> output = new DataTablesOutput<>();
    output.setDraw(input.getDraw());
    if (input.getLength() == 0) {
        return output;
    }

    try {
        long recordsTotal = count(preFilteringCriteria);
        output.setRecordsTotal(recordsTotal);
        if (recordsTotal == 0) {
            return output;
        }

        DataTablesCriteria criteria = new DataTablesCriteria(input, additionalCriteria, preFilteringCriteria);

        long recordsFiltered = mongoOperations.count(criteria.toCountQuery(), metadata.getCollectionName());
        output.setRecordsFiltered(recordsFiltered);
        if (recordsFiltered == 0) {
            return output;
        }

        List<T> data = mongoOperations.find(criteria.toQuery(), metadata.getJavaType(), metadata.getCollectionName());
        output.setData(converter == null ? (List<R>) data : data.stream().map(converter).collect(toList()));

    } catch (Exception e) {
        output.setError(e.toString());
    }

    return output;
}
 
Example #27
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);
    }
 
Example #28
Source File: ArticleRepositoryImpl.java    From jakduk-api with MIT License 5 votes vote down vote up
/**
 * id 배열에 해당하는 Article 목록.
 * @param ids id 배열
 */
@Override
public List<ArticleSimple> findArticleSimplesByIds(List<ObjectId> ids) {
    AggregationOperation match1 = Aggregation.match(Criteria.where("_id").in(ids));
    Aggregation aggregation = Aggregation.newAggregation(match1);
    AggregationResults<ArticleSimple> results = mongoTemplate.aggregate(aggregation, Constants.COLLECTION_ARTICLE, ArticleSimple.class);

    return results.getMappedResults();
}
 
Example #29
Source File: MongoCoordinatorRepository.java    From hmily with Apache License 2.0 5 votes vote down vote up
@Override
public List<HmilyTransaction> listAllByDelay(final Date date) {
    Query query = new Query();
    query.addCriteria(Criteria.where("lastTime").lt(date));
    final List<MongoAdapter> mongoBeans =
            template.find(query, MongoAdapter.class, collectionName);
    if (CollectionUtils.isNotEmpty(mongoBeans)) {
        return mongoBeans.stream().map(this::buildByCache).collect(Collectors.toList());
    }
    return Collections.emptyList();
}
 
Example #30
Source File: MongoDBArtifactStore.java    From hawkbit-extensions with Eclipse Public License 1.0 5 votes vote down vote up
private void deleteArtifact(final GridFSFile file) {
    if (file != null) {
        try {
            gridFs.delete(new Query().addCriteria(Criteria.where(ID).is(file.getId())));
        } catch (final MongoClientException e) {
            throw new ArtifactStoreException(e.getMessage(), e);
        }
    }
}