Java Code Examples for com.mongodb.client.model.Filters#and()

The following examples show how to use com.mongodb.client.model.Filters#and() . 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: MongoDbDataProviderEngine.java    From n2o-framework with Apache License 2.0 6 votes vote down vote up
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 2
Source File: DatabaseReader.java    From kafka-connect-mongodb with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the query to execute on the collection.
 *
 * @return the query
 */
private Bson createQuery() {
    // timestamps are used as offsets, saved as a concatenation of seconds and order
	Integer timestamp = 0;
    Integer order = 0;
	if(!start.equals("0")){    	
 	final String[] splitted = start.split("_");
 	timestamp = Integer.valueOf(splitted[0]);
     order = Integer.valueOf(splitted[1]);
	}
	
    Bson query = Filters.and(
            Filters.exists("fromMigrate", false),
            Filters.gt("ts", new BSONTimestamp(timestamp, order)),
            Filters.or(
                    Filters.eq("op", "i"),
                    Filters.eq("op", "u"),
                    Filters.eq("op", "d")
            ),
            Filters.eq("ns", db)
    );

    return query;
}
 
Example 3
Source File: PatchCounter.java    From repairnator with MIT License 6 votes vote down vote up
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 4
Source File: TestingTipsDao.java    From XBDD with Apache License 2.0 6 votes vote down vote up
public Map<String, TestingTips> getLatestTestingTips(final Coordinates coordinates) {
	final MongoCollection<TestingTips> collection = getTestingTipsColletions();
	final Map<String, TestingTips> rtn = new HashMap<>();

	final Bson query = Filters.and(
			Filters.eq("coordinates.product", coordinates.getProduct()),
			Filters.lte("coordinates.major", coordinates.getMajor()),
			Filters.lte("coordinates.minor", coordinates.getMinor()),
			Filters.lte("coordinates.servicePack", coordinates.getServicePack()));

	final Consumer<TestingTips> addToRtn = tt -> {
		final String key = TestingTipUtil.getMapKey(tt);
		if (rtn.containsKey(key)) {
			rtn.put(key, getNewest(rtn.get(key), tt));
		} else {
			rtn.put(key, tt);
		}
	};

	collection.find(query, TestingTips.class).forEach(addToRtn);

	return rtn;
}
 
Example 5
Source File: TimedSummaryNotifier.java    From repairnator with MIT License 6 votes vote down vote up
/**
 * Basic constructor. Sets all relevant fields.
 * @param engines
 * @param interval
 * @param tools
 * @param mongodbHost
 * @param mongodbName
 * @param notificationTime not yet implemented
 */
public TimedSummaryNotifier(List<NotifierEngine> engines, Duration interval,
        String[] tools, String mongodbHost, String mongodbName, Date notificationTime) {
    this.engines = engines;
    this.interval = interval;
    this.mongodbHost = mongodbHost;
    this.mongodbName = mongodbName;
    this.repairTools = tools;
    this.lastNotificationTime = new GregorianCalendar();
    this.lastNotificationTime.setTime(notificationTime);
    
    Date previousDate = lastNotificationTime.getTime();
    
    this.rtscannerFilter = Filters.gte("dateWatched", previousDate);   
    this.repairAttemptsFilter = Filters.and(Filters.gte("buildReproductionDate", MONGO_DATE_FORMAT.format(previousDate)),
            Filters.or(Filters.eq("status", "test failure"), Filters.eq("status", "PATCHED")));
    this.patchedBuildsFilter = Filters.and
            (Filters.gte("buildReproductionDate", previousDate), Filters.eq("status", "PATCHED"));

    this.toolFilters = new HashMap<String, Bson>();
    for (String tool : this.repairTools) {
        this.toolFilters.put(tool, Filters.and(Filters.gte("date", previousDate),
                Filters.eq("toolname", tool)));
    }
}
 
Example 6
Source File: MongoDbDeltaCollection.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@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 7
Source File: GetFilterBsonVisitor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Bson matchKeyValue(final String key) {
    final Bson keyValueFilter = Filters.and(Filters.eq(FIELD_INTERNAL_KEY, key), valueFilter);
    return Filters.elemMatch(FIELD_INTERNAL,
            getAuthorizationBson()
                    .map(authBson -> Filters.and(keyValueFilter, authBson))
                    .orElse(keyValueFilter));
}
 
Example 8
Source File: MongoThingsSearchPersistence.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Source<Metadata, NotUsed> sudoStreamMetadata(final EntityId lowerBound) {
    final Bson notDeletedFilter = Filters.exists(FIELD_DELETE_AT, false);
    final Bson filter = lowerBound.isDummy()
            ? notDeletedFilter
            : Filters.and(notDeletedFilter, Filters.gt(FIELD_ID, lowerBound.toString()));
    final Bson relevantFieldsProjection =
            Projections.include(FIELD_ID, FIELD_REVISION, FIELD_POLICY_ID, FIELD_POLICY_REVISION,
                    FIELD_PATH_MODIFIED);
    final Bson sortById = Sorts.ascending(FIELD_ID);
    final Publisher<Document> publisher = collection.find(filter)
            .projection(relevantFieldsProjection)
            .sort(sortById);
    return Source.fromPublisher(publisher).map(MongoThingsSearchPersistence::readAsMetadata);
}
 
Example 9
Source File: QueryBuilder.java    From elepy with Apache License 2.0 5 votes vote down vote up
private Bson booleanGroup(BooleanGroup expression) {
    final var groupExpressions = expression.getExpressions().stream().map(this::expression).collect(Collectors.toList());

    if (expression.getOperator().equals(BooleanGroup.BooleanOperator.AND)) {
        return Filters.and(groupExpressions);
    } else {
        return Filters.or(groupExpressions);

    }
}
 
Example 10
Source File: MongoBlockServiceImpl.java    From nuls-v2 with MIT License 5 votes vote down vote up
@Override
public int getBlockPackageTxCount(int chainId, long startHeight, long endHeight) {
    if (!CacheManager.isChainExist(chainId)) {
        return 0;
    }
    BasicDBObject fields = new BasicDBObject();
    fields.append("txCount", 1);
    Bson filter = Filters.and(Filters.gt("_id", startHeight), Filters.lte("_id", endHeight));
    List<Document> docsList = this.mongoDBService.query(BLOCK_HEADER_TABLE + chainId, filter, fields, Sorts.descending("_id"));
    int count = 0;
    for (Document document : docsList) {
        count += document.getInteger("txCount");
    }
    return count;
}
 
Example 11
Source File: MongoBlockServiceImpl.java    From nuls-v2 with MIT License 5 votes vote down vote up
public PageInfo<MiniBlockHeaderInfo> pageQuery(int chainId, int pageIndex, int pageSize, String packingAddress, boolean filterEmptyBlocks) {
    if (!CacheManager.isChainExist(chainId)) {
        return new PageInfo<>(pageIndex, pageSize);
    }
    Bson filter = null;
    if (StringUtils.isNotBlank(packingAddress)) {
        filter = Filters.eq("packingAddress", packingAddress);
    }
    if (filterEmptyBlocks) {
        if (filter == null) {
            filter = Filters.gt("txCount", 1);
        } else {
            filter = Filters.and(filter, Filters.gt("txCount", 1));
        }
    }
    long totalCount = mongoDBService.getCount(BLOCK_HEADER_TABLE + chainId, filter);
    BasicDBObject fields = new BasicDBObject();
    fields.append("_id", 1).append("createTime", 1).append("txCount", 1).append("agentHash", 1).
            append("agentId", 1).append("agentAlias", 1).append("size", 1).append("reward", 1);

    List<Document> docsList = this.mongoDBService.pageQuery(BLOCK_HEADER_TABLE + chainId, filter, fields, Sorts.descending("_id"), pageIndex, pageSize);
    List<MiniBlockHeaderInfo> list = new ArrayList<>();
    for (Document document : docsList) {
        list.add(DocumentTransferTool.toInfo(document, "height", MiniBlockHeaderInfo.class));
    }
    PageInfo<MiniBlockHeaderInfo> pageInfo = new PageInfo<>(pageIndex, pageSize, totalCount, list);
    return pageInfo;
}
 
Example 12
Source File: MongoRepository.java    From javers with Apache License 2.0 5 votes vote down vote up
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 13
Source File: MongoTransactionServiceImpl.java    From nuls-v2 with MIT License 5 votes vote down vote up
public PageInfo<MiniTransactionInfo> getTxList(int chainId, int pageIndex, int pageSize, int type,
                                               boolean isHidden, long startTime, long endTime) {
    Bson filter = null;
    if (type > 0 && startTime > 0 && endTime > 0) {
        filter = Filters.and(Filters.eq("type", type), Filters.gte("createTime", startTime), Filters.lte("createTime", endTime));
    } else if (type > 0 && startTime > 0) {
        filter = Filters.and(Filters.eq("type", type), Filters.gte("createTime", startTime));
    } else if (type > 0 && endTime > 0) {
        filter = Filters.and(Filters.eq("type", type), Filters.lte("createTime", endTime));
    } else if (type > 0) {
        filter = Filters.eq("type", type);
    } else if (isHidden && startTime > 0 && endTime > 0) {
        filter = Filters.and(ne("type", 1), Filters.gte("createTime", startTime), Filters.lte("createTime", endTime));
    } else if (isHidden && startTime > 0) {
        filter = Filters.and(ne("type", 1), Filters.gte("createTime", startTime));
    } else if (isHidden && endTime > 0) {
        filter = Filters.and(ne("type", 1), Filters.lte("createTime", endTime));
    } else if (isHidden) {
        filter = ne("type", 1);
    } else if (startTime > 0 && endTime > 0) {
        filter = Filters.and(Filters.gte("createTime", startTime), Filters.lte("createTime", endTime));
    } else if (startTime > 0) {
        filter = Filters.gte("createTime", startTime);
    } else if (endTime > 0) {
        filter = Filters.lte("createTime", endTime);
    }
    long totalCount = mongoDBService.getCount(TX_TABLE + chainId, filter);
    List<Document> docList = this.mongoDBService.pageQuery(TX_TABLE + chainId, filter, Sorts.descending("createTime"), pageIndex, pageSize);
    List<MiniTransactionInfo> txList = new ArrayList<>();
    for (Document document : docList) {
        txList.add(MiniTransactionInfo.toInfo(document));
    }

    PageInfo<MiniTransactionInfo> pageInfo = new PageInfo<>(pageIndex, pageSize, totalCount, txList);
    return pageInfo;
}
 
Example 14
Source File: MongoDbDeltaCollection.java    From swellrt with Apache License 2.0 4 votes vote down vote up
/**
 * Create Filter to match Wavelet deltas at given "applied at" version.
 *
 * @return bson filter
 */
protected Bson filterByAppliedAtVersion(long version) {

  return Filters.and(createWaveletDBQuery(),
      Filters.eq(MongoDbDeltaStoreUtil.FIELD_TRANSFORMED_APPLIEDATVERSION, version));
}
 
Example 15
Source File: MongoDbTable.java    From beam with Apache License 2.0 4 votes vote down vote up
/**
 * Recursively translates a single RexNode to MongoDB Bson filter. Supports simple comparison
 * operations, negation, and nested conjunction/disjunction. Boolean fields are translated as an
 * `$eq` operation with a boolean `true`.
 *
 * @param node {@code RexNode} to translate.
 * @return {@code Bson} filter.
 */
private Bson translateRexNodeToBson(RexNode node) {
  final IntFunction<String> fieldIdToName = i -> getSchema().getField(i).getName();
  // Supported operations are described in MongoDbFilter#isSupported
  if (node instanceof RexCall) {
    RexCall compositeNode = (RexCall) node;
    List<RexLiteral> literals = new ArrayList<>();
    List<RexInputRef> inputRefs = new ArrayList<>();

    for (RexNode operand : compositeNode.getOperands()) {
      if (operand instanceof RexLiteral) {
        literals.add((RexLiteral) operand);
      } else if (operand instanceof RexInputRef) {
        inputRefs.add((RexInputRef) operand);
      }
    }

    // Operation is a comparison, since one of the operands in a field reference.
    if (inputRefs.size() == 1) {
      RexInputRef inputRef = inputRefs.get(0);
      String inputFieldName = fieldIdToName.apply(inputRef.getIndex());
      if (literals.size() > 0) {
        // Convert literal value to the same Java type as the field we are comparing to.
        Object literal = convertToExpectedType(inputRef, literals.get(0));

        switch (node.getKind()) {
          case IN:
            return Filters.in(inputFieldName, convertToExpectedType(inputRef, literals));
          case EQUALS:
            return Filters.eq(inputFieldName, literal);
          case NOT_EQUALS:
            return Filters.not(Filters.eq(inputFieldName, literal));
          case LESS_THAN:
            return Filters.lt(inputFieldName, literal);
          case GREATER_THAN:
            return Filters.gt(inputFieldName, literal);
          case GREATER_THAN_OR_EQUAL:
            return Filters.gte(inputFieldName, literal);
          case LESS_THAN_OR_EQUAL:
            return Filters.lte(inputFieldName, literal);
          default:
            // Encountered an unexpected node kind, RuntimeException below.
            break;
        }
      } else if (node.getKind().equals(SqlKind.NOT)) {
        // Ex: `where not boolean_field`
        return Filters.not(translateRexNodeToBson(inputRef));
      } else {
        throw new RuntimeException(
            "Cannot create a filter for an unsupported node: " + node.toString());
      }
    } else { // Operation is a conjunction/disjunction.
      switch (node.getKind()) {
        case AND:
          // Recursively construct filter for each operand of conjunction.
          return Filters.and(
              compositeNode.getOperands().stream()
                  .map(this::translateRexNodeToBson)
                  .collect(Collectors.toList()));
        case OR:
          // Recursively construct filter for each operand of disjunction.
          return Filters.or(
              compositeNode.getOperands().stream()
                  .map(this::translateRexNodeToBson)
                  .collect(Collectors.toList()));
        default:
          // Encountered an unexpected node kind, RuntimeException below.
          break;
      }
    }
    throw new RuntimeException(
        "Encountered an unexpected node kind: " + node.getKind().toString());
  } else if (node instanceof RexInputRef
      && node.getType().getSqlTypeName().equals(SqlTypeName.BOOLEAN)) {
    // Boolean field, must be true. Ex: `select * from table where bool_field`
    return Filters.eq(fieldIdToName.apply(((RexInputRef) node).getIndex()), true);
  }

  throw new RuntimeException(
      "Was expecting a RexCall or a boolean RexInputRef, but received: "
          + node.getClass().getSimpleName());
}
 
Example 16
Source File: CreateBsonVisitor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Bson visitAnd(final List<Bson> conjuncts) {
    return Filters.and(conjuncts);
}
 
Example 17
Source File: TestFilter.java    From jframe with Apache License 2.0 4 votes vote down vote up
@Test
public void test() {
    Bson b = Filters.and(Filters.eq("n1", "v1"), Filters.lt("n2", "v2"));
    System.out.println(JSON.serialize(b));
}
 
Example 18
Source File: MongoDbDeltaCollection.java    From swellrt with Apache License 2.0 4 votes vote down vote up
/**
 * Create Filter to match Wavelet deltas at given "resulting" version.
 *
 * @return bson filter
 */
protected Bson filterByResultingVersion(long version) {

  return Filters.and(createWaveletDBQuery(),
      Filters.eq(MongoDbDeltaStoreUtil.FIELD_TRANSFORMED_RESULTINGVERSION_VERSION, version));
}
 
Example 19
Source File: MongoPublishedVersionStore.java    From enode with MIT License 4 votes vote down vote up
@Override
public CompletableFuture<Integer> getPublishedVersionAsync(String processorName, String aggregateRootTypeName, String aggregateRootId) {
    CompletableFuture<Integer> future = new CompletableFuture<>();
    Bson updateFilter = Filters.and(
            Filters.eq("processorName", processorName),
            Filters.eq("aggregateRootId", aggregateRootId)
    );
    mongoClient.getDatabase(configuration.getDatabaseName()).getCollection(configuration.getPublishedVersionCollectionName()).find(updateFilter).subscribe(new Subscriber<Document>() {
        private Integer version = 0;

        @Override
        public void onSubscribe(Subscription s) {
            s.request(1);
        }

        @Override
        public void onNext(Document document) {
            version = document.getInteger("version");
            future.complete(version);
        }

        @Override
        public void onError(Throwable t) {
            future.completeExceptionally(t);
        }

        @Override
        public void onComplete() {
            future.complete(version);
        }
    });
    return future.exceptionally(throwable -> {
        if (throwable instanceof SQLException) {
            SQLException ex = (SQLException) throwable;
            logger.error("Get aggregate published version has sql exception.", ex);
            throw new IORuntimeException(throwable);
        }
        logger.error("Get aggregate published version has unknown exception.", throwable);
        throw new EnodeRuntimeException(throwable);
    });
}
 
Example 20
Source File: AbstractWriteModel.java    From ditto with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Get the filter of this write model.
 *
 * @return filter on search index documents.
 */
public Bson getFilter() {
    return Filters.and(Filters.eq(FIELD_ID, new BsonString(metadata.getThingId().toString())));
}