com.mongodb.client.model.Filters Java Examples
The following examples show how to use
com.mongodb.client.model.Filters.
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: PatchCounter.java From repairnator with MIT License | 6 votes |
public PatchCounter(int numberOfPatchesToRunFor, String mongodbHost, String mongodbName, Date startDate, InspectBuilds inspectBuilds, InspectJobs inspectJobs) { // Set the variables this.numberOfPatchesToRunFor = numberOfPatchesToRunFor; this.mongodbHost = mongodbHost; this.mongodbName = mongodbName; // Create a filter that fetches each patch-document since the scanner started this.patchesFilter = Filters.gte("date", startDate); this.buildFilter = Filters.and( Filters.gte("buildFinishedDate", startDate), Filters.eq("status", "PATCHED")); }
Example #2
Source File: MongoCollectionImpl.java From core-ng-project with Apache License 2.0 | 6 votes |
@Override public long bulkDelete(List<?> ids) { var watch = new StopWatch(); int size = ids.size(); int deletedRows = 0; try { List<DeleteOneModel<T>> models = new ArrayList<>(size); for (Object id : ids) { models.add(new DeleteOneModel<>(Filters.eq("_id", id))); } BulkWriteResult result = collection().bulkWrite(models, new BulkWriteOptions().ordered(false)); deletedRows = result.getDeletedCount(); return deletedRows; } finally { long elapsed = watch.elapsed(); ActionLogContext.track("mongo", elapsed, 0, deletedRows); logger.debug("bulkDelete, collection={}, ids={}, size={}, deletedRows={}, elapsed={}", collectionName, ids, size, deletedRows, elapsed); checkSlowOperation(elapsed); } }
Example #3
Source File: MongoCollectionImpl.java From core-ng-project with Apache License 2.0 | 6 votes |
@Override public void replace(T entity) { var watch = new StopWatch(); Object id = null; validator.validate(entity); try { id = mongo.codecs.id(entity); if (id == null) throw new Error(format("entity must have id, entityClass={}", entityClass.getCanonicalName())); collection().replaceOne(Filters.eq("_id", id), entity, new ReplaceOptions().upsert(true)); } finally { long elapsed = watch.elapsed(); ActionLogContext.track("mongo", elapsed, 0, 1); logger.debug("replace, collection={}, id={}, elapsed={}", collectionName, id, elapsed); checkSlowOperation(elapsed); } }
Example #4
Source File: TagAssignmentDao.java From XBDD with Apache License 2.0 | 6 votes |
public void saveTagAssignment(final Coordinates coordinates, final SingleTagAssignment singleTagAssignment) { final MongoCollection<TagAssignments> tagAssignments = getTagAssignmentColletions(); final CoordinatesDto coordinatesDto = CoordinatesMapper.mapCoordinates(coordinates); final Bson query = Filters.eq("coordinates", coordinatesDto); final TagAssignments savedAssignments = tagAssignments.find(query).first(); if (savedAssignments == null) { final TagAssignments newAssignments = new TagAssignments(); newAssignments.setCoordinates(coordinatesDto); newAssignments.setTags(Arrays.asList(singleTagAssignment)); tagAssignments.insertOne(newAssignments); } else { savedAssignments.getTags().removeIf(single -> single.getTag().equals(singleTagAssignment.getTag())); savedAssignments.getTags().add(singleTagAssignment); tagAssignments.replaceOne(query, savedAssignments); } }
Example #5
Source File: DBUser.java From Shadbot with GNU General Public License v3.0 | 6 votes |
private Mono<UpdateResult> updateAchievement(int achievements) { // If the achievement is already in this state, no need to request an update if (this.getBean().getAchievements() == achievements) { LOGGER.debug("[DBUser {}] Achievements update useless, aborting: {}", this.getId().asLong(), achievements); return Mono.empty(); } LOGGER.debug("[DBUser {}] Achievements update: {}", this.getId().asLong(), achievements); return Mono.from(DatabaseManager.getUsers() .getCollection() .updateOne( Filters.eq("_id", this.getId().asString()), Updates.set("achievements", achievements), new UpdateOptions().upsert(true))) .doOnNext(result -> LOGGER.trace("[DBUser {}] Achievements update result: {}", this.getId().asLong(), result)) .doOnTerminate(() -> DB_REQUEST_COUNTER.labels(UsersCollection.NAME).inc()); }
Example #6
Source File: MongoDBConnectorInsertTest.java From syndesis with Apache License 2.0 | 6 votes |
@Test public void mongoInsertSingleTest() { // When String uniqueId = UUID.randomUUID().toString(); String message = String.format("{\"test\":\"unit\",\"uniqueId\":\"%s\"}", uniqueId); Document doc = Document.parse(message); // Given @SuppressWarnings("unchecked") List<String> resultsAsString = template.requestBody("direct:start", message, List.class); // Then Assertions.assertThat(resultsAsString).hasSize(1); Document result = resultsAsString.stream().map(Document::parse).collect(Collectors.toList()).get(0); Assertions.assertThat(doc.getString("test")).isEqualTo(result.getString("test")); Assertions.assertThat(doc.getString("uniqueId")).isEqualTo(result.getString("uniqueId")); List<Document> docsFound = collection.find(Filters.eq("uniqueId", uniqueId)).into(new ArrayList<>()); Assertions.assertThat(docsFound).hasSize(1); Assertions.assertThat(docsFound).contains(result); }
Example #7
Source File: MongoDbIOTest.java From beam with Apache License 2.0 | 6 votes |
@Test public void testReadWithFilterAndLimit() throws Exception { PCollection<Document> output = pipeline.apply( MongoDbIO.read() .withUri("mongodb://localhost:" + port) .withDatabase(DATABASE) .withCollection(COLLECTION) .withNumSplits(10) .withQueryFn( FindQuery.create() .withFilters(Filters.eq("scientist", "Einstein")) .withLimit(5))); PAssert.thatSingleton(output.apply("Count", Count.globally())).isEqualTo(5L); pipeline.run(); }
Example #8
Source File: DBMember.java From Shadbot with GNU General Public License v3.0 | 6 votes |
@Override public Mono<Void> delete() { LOGGER.debug("[DBMember {} / {}] Deletion", this.getId().asLong(), this.getGuildId().asLong()); return Mono.from(DatabaseManager.getGuilds() .getCollection() .updateOne(Filters.eq("_id", this.getGuildId().asString()), Updates.pull("members", Filters.eq("_id", this.getId().asString())))) .doOnNext(result -> LOGGER.trace("[DBMember {} / {}] Deletion result: {}", this.getId().asLong(), this.getGuildId().asLong(), result)) .doOnTerminate(() -> DB_REQUEST_COUNTER.labels(GuildsCollection.NAME).inc()) .then(); }
Example #9
Source File: MongoCompensableRepository.java From ByteTCC with GNU Lesser General Public License v3.0 | 6 votes |
private void markTransactionRollback(TransactionXid transactionXid) { try { byte[] global = transactionXid.getGlobalTransactionId(); String identifier = ByteUtils.byteArrayToString(global); String application = CommonUtils.getApplication(this.endpoint); String databaseName = application.replaceAll("\\W", "_"); MongoDatabase mdb = this.mongoClient.getDatabase(databaseName); MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_TRANSACTIONS); Document document = new Document(); document.append("$set", new Document("status", Status.STATUS_MARKED_ROLLBACK)); Bson globalFilter = Filters.eq(CONSTANTS_FD_GLOBAL, identifier); Bson statusFilter = Filters.eq("status", Status.STATUS_ACTIVE); collection.updateOne(Filters.and(globalFilter, statusFilter), document); } catch (RuntimeException error) { logger.error("Error occurred while setting the error flag.", error); } }
Example #10
Source File: MongoDBFactory.java From database-transform-tool with Apache License 2.0 | 6 votes |
/** * @decription 删除数据 * @author yi.zhang * @time 2017年6月2日 下午6:19:25 * @param table 文档名称(表名) * @param obj * @return */ public int delete(String table, Object obj) { try { if(session==null){ init(servers, database, schema, username, password); } MongoCollection<Document> collection = session.getCollection(table); if (collection == null) { return 0; } JSONObject json = JSON.parseObject(JSON.toJSONString(obj)); collection.findOneAndDelete(Filters.eq("_id", json.containsKey("_id")?json.get("_id"):json.get("id"))); return 1; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return -1; }
Example #11
Source File: FeatureDao.java From XBDD with Apache License 2.0 | 6 votes |
public List<XbddFeatureSummary> getFeatureSummaries(final Coordinates coordinates) { final MongoCollection<XbddFeature> features = getFeatureCollection(); final List<XbddFeatureSummary> summaries = new ArrayList<>(); final Bson query = Filters.eq("coordinates", CoordinatesMapper.mapCoordinates(coordinates)); final FindIterable<XbddFeatureSummary> savedFeatures = features.find(query, XbddFeatureSummary.class); final Consumer<XbddFeatureSummary> addToSummaries = feature -> { if (featureIsValid(feature)) { summaries.add(feature); } }; savedFeatures.forEach(addToSummaries); return summaries; }
Example #12
Source File: RefreshOperation.java From jpa-unit with Apache License 2.0 | 6 votes |
@Override public void execute(final MongoDatabase connection, final Document data) { for (final String collectionName : data.keySet()) { final MongoCollection<Document> collection = connection.getCollection(collectionName); @SuppressWarnings("unchecked") final List<Document> documents = data.get(collectionName, List.class); for (final Document doc : documents) { final UpdateResult result = collection.replaceOne(Filters.eq(doc.get("_id")), doc); if (result.getMatchedCount() == 0) { collection.insertOne(doc); } } } }
Example #13
Source File: MongoDbDataProviderEngine.java From n2o-framework with Apache License 2.0 | 6 votes |
private Bson getFilters(Map<String, Object> inParams) { Bson filters = null; if (inParams.containsKey(FILTERS) && inParams.get(FILTERS) != null) { PlaceHoldersResolver resolver = new PlaceHoldersResolver("#", ""); List<String> filterList = (List<String>) inParams.get(FILTERS); List<Bson> filtersByFields = new ArrayList<>(); for (String filter : filterList) { Bson f = BasicDBObject.parse(resolver.resolve(filter, PlaceHoldersResolver.replaceByJson(replaceOptional(inParams::get), mapper))); filtersByFields.add(f); } filters = filtersByFields.isEmpty() ? null : Filters.and(filtersByFields); } return filters; }
Example #14
Source File: Relic.java From Shadbot with GNU General Public License v3.0 | 5 votes |
public Mono<UpdateResult> activate(Snowflake userId, @Nullable Snowflake guildId) { LOGGER.debug("[Relic {}] Activation", this.getId()); return Mono.from(DatabaseManager.getPremium() .getCollection() .updateOne(Filters.eq("_id", this.getId()), Updates.combine( Updates.set("user_id", userId.asString()), Updates.set("guild_id", guildId == null ? null : guildId.asString()), Updates.set("activation", Instant.now().toEpochMilli())))) .doOnNext(result -> LOGGER.trace("[Relic {}] Activation result; {}", this.getId(), result)); }
Example #15
Source File: MongoDbDeltaCollection.java From swellrt with Apache License 2.0 | 5 votes |
@Override public long getDeltasInRange(long startVersion, long endVersion, Receiver<WaveletDeltaRecord> receiver) throws IOException { boolean ascendingSort = startVersion < endVersion; BasicDBObject sort = new BasicDBObject(); sort.put(MongoDbDeltaStoreUtil.FIELD_TRANSFORMED_RESULTINGVERSION_VERSION, ascendingSort ? 1 : -1); Bson query = null; if (ascendingSort) { query = Filters.and(createWaveletDBQuery(), Filters.gte(MongoDbDeltaStoreUtil.FIELD_TRANSFORMED_APPLIEDATVERSION, startVersion), Filters.lte(MongoDbDeltaStoreUtil.FIELD_TRANSFORMED_RESULTINGVERSION_VERSION, endVersion)); } else { query = Filters.and(createWaveletDBQuery(), Filters.gte(MongoDbDeltaStoreUtil.FIELD_TRANSFORMED_APPLIEDATVERSION, endVersion), Filters.lte(MongoDbDeltaStoreUtil.FIELD_TRANSFORMED_RESULTINGVERSION_VERSION, startVersion)); } DeltaReader block = new DeltaReader(receiver, ascendingSort); try { deltasCollection.find(query).sort(sort).forEach(block); } catch (DeltaReaderHaltedException e) { } if (block.exception != null) throw new IOException(block.exception); return block.count; }
Example #16
Source File: FindVisitor.java From immutables with Apache License 2.0 | 5 votes |
/** * see https://docs.mongodb.com/manual/reference/operator/query/not/ * NOT operator is mongo is a little specific and can't be applied on all levels * $not: { $or ... } will not work and should be transformed to $nor */ private Bson negate(Expression expression) { if (!(expression instanceof Call)) { return Filters.not(expression.accept(this)); } Call notCall = (Call) expression; if (notCall.operator() == Operators.NOT) { // NOT NOT a == a return notCall.arguments().get(0).accept(this); } else if (notCall.operator() == Operators.EQUAL) { return visit(Expressions.call(Operators.NOT_EQUAL, notCall.arguments())); } else if (notCall.operator() == Operators.NOT_EQUAL) { return visit(Expressions.call(Operators.EQUAL, notCall.arguments())); } else if (notCall.operator() == Operators.IN) { return visit(Expressions.call(Operators.NOT_IN, notCall.arguments())); } else if (notCall.operator() == Operators.NOT_IN) { return visit(Expressions.call(Operators.IN, notCall.arguments())); } else if (notCall.operator() == Operators.OR) { return Filters.nor(notCall.arguments().stream().map(a -> a.accept(this)).collect(Collectors.toList())); } else if (notCall.operator() == Operators.AND) { // NOT A and B == (NOT A) or (NOT B) return Filters.or(notCall.arguments().stream().map(this::negate).collect(Collectors.toList())); } // don't really know how to negate here return Filters.not(notCall.accept(this)); }
Example #17
Source File: MongoCollectionImpl.java From core-ng-project with Apache License 2.0 | 5 votes |
@Override public boolean delete(Object id) { var watch = new StopWatch(); long deletedRows = 0; try { DeleteResult result = collection().deleteOne(Filters.eq("_id", id)); deletedRows = result.getDeletedCount(); return deletedRows == 1; } finally { long elapsed = watch.elapsed(); ActionLogContext.track("mongo", elapsed, 0, (int) deletedRows); logger.debug("delete, collection={}, id={}, elapsed={}", collectionName, id, elapsed); checkSlowOperation(elapsed); } }
Example #18
Source File: MongoRepository.java From javers with Apache License 2.0 | 5 votes |
private Bson addCommitPropertiesFilter(Bson query, Map<String, String> commitProperties) { List<Bson> propertyFilters = commitProperties.entrySet().stream().map( commitProperty -> new BasicDBObject(COMMIT_PROPERTIES, new BasicDBObject("$elemMatch", new BasicDBObject("key", commitProperty.getKey()).append( "value", commitProperty.getValue()))) ).collect(toImmutableList()); return Filters.and(query, Filters.and(propertyFilters.toArray(new Bson[]{}))); }
Example #19
Source File: MongoStatisticalServiceImpl.java From nuls-v2 with MIT License | 5 votes |
@Override public ChainStatisticalInfo getChainStatisticalInfo(int chainId) { Document document = mongoDBService.findOne(CHAIN_STATISTICAL_TABLE, Filters.eq("chainId", chainId)); if (document == null) { return null; } return DocumentTransferTool.toInfo(document, ChainStatisticalInfo.class); }
Example #20
Source File: MongoGeospatialLiveTest.java From tutorials with MIT License | 5 votes |
@Test public void givenNearbyLocation_whenSearchUsingIntersect_thenFound() { ArrayList<Position> positions = new ArrayList<Position>(); positions.add(new Position(-0.1439, 51.4952)); positions.add(new Position(-0.1346, 51.4978)); positions.add(new Position(-0.2177, 51.5135)); positions.add(new Position(-0.1439, 51.4952)); Polygon geometry = new Polygon(positions); FindIterable<Document> result = collection.find(Filters.geoIntersects("location", geometry)); assertNotNull(result.first()); assertEquals("Hyde Park", result.first().get("name")); }
Example #21
Source File: MongoResourceStorage.java From EDDI with Apache License 2.0 | 5 votes |
@Override public IHistoryResource<T> readHistory(String id, Integer version) { Document objectId = new Document(ID_FIELD, new ObjectId(id)); objectId.put(VERSION_FIELD, version); Document doc = historyCollection.find(Filters.eq(ID_FIELD, objectId)).first(); if (doc == null) { return null; } return new HistoryResource(doc); }
Example #22
Source File: MongoBlockServiceImpl.java From nuls-v2 with MIT License | 5 votes |
@Override public BlockHexInfo getBlockHexInfo(int chainId, String hash) { Document document = mongoDBService.findOne(BLOCK_HEADER_TABLE + chainId, Filters.eq("hash", hash)); if (document == null) { return null; } long height = document.getLong("_id"); document = mongoDBService.findOne(BLOCK_HEX_TABLE + chainId, Filters.eq("_id", height)); if (document == null) { return null; } return DocumentTransferTool.toInfo(document, "height", BlockHexInfo.class); }
Example #23
Source File: MongoBlockServiceImpl.java From nuls-v2 with MIT License | 5 votes |
@Override public BigInteger getLast24HourRewards(int chainId) { long time = System.currentTimeMillis() / 1000; time = time - 24 * 60 * 60; Bson filter = Filters.gte("createTime", time); BasicDBObject fields = new BasicDBObject(); fields.append("reward", 1); BigInteger reward = BigInteger.ZERO; List<Document> docsList = this.mongoDBService.query(BLOCK_HEADER_TABLE + chainId, filter, fields); for (Document document : docsList) { reward = reward.add(new BigInteger(document.getString("reward"))); } return reward; }
Example #24
Source File: MongoIntegrationTest.java From core-ng-project with Apache License 2.0 | 5 votes |
@Test void find() { TestMongoEntity entity = createEntity("value2", TestMongoEntity.TestEnum.VALUE2); List<TestMongoEntity> entities = collection.find(Filters.eq("string_field", "value2")); assertThat(entities).hasSize(1).first().isEqualToComparingFieldByField(entity); }
Example #25
Source File: MongoDBConnectorSaveTest.java From syndesis with Apache License 2.0 | 5 votes |
@Test public void mongoSaveNewTest() { // When // Given String saveArguments = "{\"id\":11,\"someText\":\"new\"}"; UpdateResult result = template.requestBody("direct:start", saveArguments, UpdateResult.class); // Then Assertions.assertThat(result.getUpsertedId().asNumber().longValue()).isEqualTo(11L); List<Document> docsFound = collection.find(Filters.eq("_id", 11)).into(new ArrayList<>()); Assertions.assertThat(docsFound).hasSize(1); Assertions.assertThat(docsFound.get(0).getString("test")).isEqualTo("new"); }
Example #26
Source File: ChatActionMongodb.java From anychat with MIT License | 5 votes |
public static long getGroupChatNum(String toTypeId, String chatCreateTime) { if (StringUtil.stringIsNull(toTypeId)) { return 0; } Date date = null; if (!StringUtil.stringIsNull(chatCreateTime)) { date = TimeUtils.stringToDateDay(chatCreateTime); } Bson filter = null; if (!StringUtil.stringIsNull(chatCreateTime)) { filter = Filters.lt(ChatObj.CHAT_CREATE_TIME, String.valueOf(date.getTime())); } long count = MongodbManager.count(toTypeId, filter); return count; }
Example #27
Source File: MongoGeospatialLiveTest.java From tutorials with MIT License | 5 votes |
@Test public void givenNearbyLocation_whenSearchWithinBox_thenFound() { double lowerLeftX = -0.1427638; double lowerLeftY = 51.4991288; double upperRightX = -0.1256209; double upperRightY = 51.5030272; FindIterable<Document> result = collection.find(Filters.geoWithinBox("location", lowerLeftX, lowerLeftY, upperRightX, upperRightY)); assertNotNull(result.first()); assertEquals("Big Ben", result.first().get("name")); }
Example #28
Source File: TimedSummaryNotifier.java From repairnator with MIT License | 5 votes |
/** * Update the filters such that the previousdate is instead used when querying * the database * * @param previousDate * the date that the filters should be based on */ protected void updateFilters(Date previousDate) { this.rtscannerFilter = Filters.gte("dateWatched", previousDate); this.patchedBuildsFilter = Filters.and(Filters.gte("buildReproductionDate", previousDate), Filters.eq("status", "PATCHED")); this.repairAttemptsFilter = Filters.and(Filters.gte("buildReproductionDate", previousDate), Filters.or(Filters.eq("status", "test failure"), Filters.eq("status", "PATCHED"))); // Fetch the tools from config make map from name to filter this.toolFilters = new HashMap<String, Bson>(); for (String tool : repairTools) { this.toolFilters.put(tool, Filters.and(Filters.gte("date", previousDate), Filters.eq("toolname", tool))); } }
Example #29
Source File: ChatActionMongodb.java From anychat with MIT License | 5 votes |
public static ChatObj getChatById(String chatId, String chatGroupId) { if (StringUtil.stringIsNull(chatId) || StringUtil.stringIsNull(chatGroupId)) { return null; } Bson filter = Filters.eq(ChatObj.CHAT_ID, chatId); List<ChatObj> list = MongodbManager.find(chatGroupId, filter, ChatObj.class, 0, 0); if (list != null && list.size() != 0) { return list.get(0); } else { return null; } }
Example #30
Source File: PremiumCollection.java From Shadbot with GNU General Public License v3.0 | 5 votes |
/** * @param userId The {@link Snowflake} ID of the {@link User}. * @return A {@link Flux} containing the {@link Relic} possessed by an {@link User}. */ public Flux<Relic> getUserRelics(Snowflake userId) { LOGGER.debug("[Premium] Request relics for user {}", userId.asLong()); final Publisher<Document> request = this.getCollection() .find(Filters.eq("user_id", userId.asString())); return Flux.from(request) .map(document -> document.toJson(JSON_WRITER_SETTINGS)) .flatMap(json -> Mono.fromCallable(() -> NetUtils.MAPPER.readValue(json, RelicBean.class))) .map(Relic::new) .doOnTerminate(() -> DB_REQUEST_COUNTER.labels(PremiumCollection.NAME).inc()); }