Example usage for com.mongodb.client.model Filters in

List of usage examples for com.mongodb.client.model Filters in

Introduction

In this page you can find the example usage for com.mongodb.client.model Filters in.

Prototype

public static <TItem> Bson in(final String fieldName, final Iterable<TItem> values) 

Source Link

Document

Creates a filter that matches all documents where the value of a field equals any value in the list of specified values.

Usage

From source file:com.egopulse.querydsl.mongodb.MongodbSerializer.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from w  w  w  . j av a  2 s  . c o  m*/
public Object visit(Operation<?> expr, Void context) {
    Operator op = expr.getOperator();

    /**
     * user.firstName.eq("test")
     * user.addresses.size().eq(20)
     */
    if (op == Ops.EQ) {
        return handleEqOperation(expr);
    }

    /**
     * user.firstName.ne("test")
     */
    else if (op == Ops.NE) {
        return Filters.ne(asDBKey(expr, 0), asDBValue(expr, 1));

    }

    /**
     * user.firstName.isEmpty()
      */
    else if (op == Ops.STRING_IS_EMPTY) {
        return Filters.eq(asDBKey(expr, 0), new BsonString(""));
    }

    /**
     * user.firstName.eq("test").and(user.lastName.eq("blah"))
     */
    else if (op == Ops.AND) {
        Bson leftOperation = (Bson) handle(expr.getArg(0));
        Bson rightOperation = (Bson) handle(expr.getArg(1));

        return Filters.and(leftOperation, rightOperation);
    }

    /**
     * user.firstName.not[Operation]
     */
    else if (op == Ops.NOT) {
        //Handle the not's child
        Operation<?> subOperation = (Operation<?>) expr.getArg(0);
        Operator subOp = subOperation.getOperator();
        if (subOp == Ops.IN) {
            return visit(ExpressionUtils.operation(Boolean.class, Ops.NOT_IN, subOperation.getArg(0),
                    subOperation.getArg(1)), context);
        } else {
            Bson arg = (Bson) handle(expr.getArg(0));
            return Filters.not(arg);
        }
    }

    /**
     * user.firstName.eq("test").or(user.firstName.eq("else"))
     */
    else if (op == Ops.OR) {
        Bson leftOperation = (Bson) handle(expr.getArg(0));
        Bson rightOperation = (Bson) handle(expr.getArg(1));
        return Filters.or(leftOperation, rightOperation);
    }

    /**
     * Text matching operations
     */
    else if (op == Ops.STARTS_WITH) {
        return Filters.regex(asDBKey(expr, 0), Pattern.compile("^" + regexValue(expr, 1)));

    }

    else if (op == Ops.STARTS_WITH_IC) {
        return Filters.regex(asDBKey(expr, 0),
                Pattern.compile("^" + regexValue(expr, 1), Pattern.CASE_INSENSITIVE));

    }

    else if (op == Ops.ENDS_WITH) {
        return Filters.regex(asDBKey(expr, 0), Pattern.compile(regexValue(expr, 1) + "$"));

    }

    else if (op == Ops.ENDS_WITH_IC) {
        return Filters.regex(asDBKey(expr, 0),
                Pattern.compile(regexValue(expr, 1) + "$", Pattern.CASE_INSENSITIVE));

    }

    else if (op == Ops.EQ_IGNORE_CASE) {
        return Filters.regex(asDBKey(expr, 0),
                Pattern.compile("^" + regexValue(expr, 1) + "$", Pattern.CASE_INSENSITIVE));

    }

    else if (op == Ops.STRING_CONTAINS) {
        return Filters.regex(asDBKey(expr, 0), Pattern.compile(".*" + regexValue(expr, 1) + ".*"));

    }

    else if (op == Ops.STRING_CONTAINS_IC) {
        return Filters.regex(asDBKey(expr, 0),
                Pattern.compile(".*" + regexValue(expr, 1) + ".*", Pattern.CASE_INSENSITIVE));

    }

    else if (op == Ops.MATCHES) {
        return Filters.regex(asDBKey(expr, 0), Pattern.compile(asDBValue(expr, 1).toString()));
    }

    else if (op == Ops.MATCHES_IC) {
        return Filters.regex(asDBKey(expr, 0),
                Pattern.compile(asDBValue(expr, 1).toString(), Pattern.CASE_INSENSITIVE));

    }

    else if (op == Ops.LIKE) {
        String regex = ExpressionUtils.likeToRegex((Expression) expr.getArg(1)).toString();
        return Filters.regex(asDBKey(expr, 0), Pattern.compile(regex));

    }

    else if (op == Ops.BETWEEN) {
        return Filters.and(Filters.gte(asDBKey(expr, 0), asDBValue(expr, 1)),
                Filters.lte(asDBKey(expr, 0), asDBValue(expr, 2)));
    }

    else if (op == Ops.IN) {
        int constIndex = 0;
        int exprIndex = 1;
        if (expr.getArg(1) instanceof Constant<?>) {
            constIndex = 1;
            exprIndex = 0;
        }
        if (Collection.class.isAssignableFrom(expr.getArg(constIndex).getType())) {
            @SuppressWarnings("unchecked") //guarded by previous check
            Collection<?> values = ((Constant<? extends Collection<?>>) expr.getArg(constIndex)).getConstant();
            return Filters.in(asDBKey(expr, exprIndex), values);
        }

        /**
         * user.firstName.in(user.lastName)
         */

        else {
            throw new UnsupportedOperationException();
            //                Path<?> path = (Path<?>) expr.getArg(exprIndex);
            //                Constant<?> constant = (Constant<?>) expr.getArg(constIndex);
            //                return asDBObject(asDBKey(expr, exprIndex), convert(path, constant));
        }

    }

    else if (op == Ops.NOT_IN) {
        int constIndex = 0;
        int exprIndex = 1;
        if (expr.getArg(1) instanceof Constant<?>) {
            constIndex = 1;
            exprIndex = 0;
        }
        if (Collection.class.isAssignableFrom(expr.getArg(constIndex).getType())) {
            @SuppressWarnings("unchecked") //guarded by previous check
            Collection<?> values = ((Constant<? extends Collection<?>>) expr.getArg(constIndex)).getConstant();
            return Filters.nin(asDBKey(expr, exprIndex), values);
        } else {
            throw new UnsupportedOperationException();
            //                Path<?> path = (Path<?>) expr.getArg(exprIndex);
            //                Constant<?> constant = (Constant<?>) expr.getArg(constIndex);
            //                return asDBObject(asDBKey(expr, exprIndex), asDBObject("$ne", convert(path, constant)));
        }

    }

    else if (op == Ops.COL_IS_EMPTY) {
        String field = asDBKey(expr, 0);
        return Filters.or(Filters.exists(field, false), Filters.size(field, 0));
    }

    else if (op == Ops.LT) {
        return Filters.lt(asDBKey(expr, 0), asDBValue(expr, 1));

    } else if (op == Ops.GT) {
        return Filters.gt(asDBKey(expr, 0), asDBValue(expr, 1));

    } else if (op == Ops.LOE) {
        return Filters.lte(asDBKey(expr, 0), asDBValue(expr, 1));

    } else if (op == Ops.GOE) {
        return Filters.gte(asDBKey(expr, 0), asDBValue(expr, 1));

    } else if (op == Ops.IS_NULL) {
        return Filters.exists(asDBKey(expr, 0), false);

    } else if (op == Ops.IS_NOT_NULL) {
        return Filters.exists(asDBKey(expr, 0), true);

    }

    else if (op == Ops.CONTAINS_KEY) {
        Path<?> path = (Path<?>) expr.getArg(0);
        Expression<?> key = expr.getArg(1);
        return Filters.exists(visit(path, context) + "." + key.toString(), true);

    }
    //        else if (op == MongodbOps.NEAR) {
    //            return asDBObject(asDBKey(expr, 0), asDBObject("$near", asDBValue(expr, 1)));
    //
    //        } else if (op == MongodbOps.NEAR_SPHERE) {
    //            return asDBObject(asDBKey(expr, 0), asDBObject("$nearSphere", asDBValue(expr, 1)));
    //
    //        }
    //        else if (op == MongodbOps.ELEM_MATCH) {
    //            return Filters.elemMatch(asDBKey(expr, 0), asDBValue(expr, 1));
    //        }

    throw new UnsupportedOperationException("Illegal operation " + expr);
}

From source file:com.epam.dlab.backendapi.dao.azure.AzureBillingDAO.java

License:Apache License

private List<Bson> matchCriteria(AzureBillingFilter filter) {

    List<Bson> searchCriteria = new ArrayList<>();

    if (filter.getUser() != null && !filter.getUser().isEmpty()) {
        searchCriteria.add(Filters.in(MongoKeyWords.DLAB_USER, filter.getUser()));
    }/*from   w w  w. jav a 2  s .  co  m*/

    if (filter.getCategory() != null && !filter.getCategory().isEmpty()) {
        searchCriteria.add(Filters.in(MongoKeyWords.METER_CATEGORY, filter.getCategory()));
    }

    if (filter.getResourceType() != null && !filter.getResourceType().isEmpty()) {
        searchCriteria.add(Filters.in(MongoKeyWords.RESOURCE_TYPE,
                DlabResourceType.getResourceTypeIds(filter.getResourceType())));
    }

    if (filter.getDlabId() != null && !filter.getDlabId().isEmpty()) {
        searchCriteria.add(regex(MongoKeyWords.DLAB_ID, filter.getDlabId(), "i"));
    }

    if (filter.getDateStart() != null && !filter.getDateStart().isEmpty()) {
        searchCriteria.add(gte(MongoKeyWords.USAGE_DAY, filter.getDateStart()));
    }
    if (filter.getDateEnd() != null && !filter.getDateEnd().isEmpty()) {
        searchCriteria.add(lte(MongoKeyWords.USAGE_DAY, filter.getDateEnd()));
    }

    return searchCriteria;
}

From source file:com.px100systems.data.plugin.storage.mongo.FilterQueryBuilder.java

License:Open Source License

@Override
public Bson convert(in predicate) {
    return Filters.in(predicate.getMember(), predicate.getList());
}

From source file:documentation.ChangeStreamSamples.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 *//*from w  w w  .  j ava2s .  c o m*/
public static void main(final String[] args) {
    MongoClient mongoClient;

    if (args.length == 0) {
        // connect to the local database server
        mongoClient = MongoClients.create("mongodb://localhost:27017,localhost:27018,localhost:27019");
    } else {
        mongoClient = MongoClients.create(args[0]);
    }

    // Select the MongoDB database.
    MongoDatabase database = mongoClient.getDatabase("testChangeStreams");
    database.drop();
    sleep();

    // Select the collection to query.
    MongoCollection<Document> collection = database.getCollection("documents");

    /*
     * Example 1
     * Create a simple change stream against an existing collection.
     */
    System.out.println("1. Initial document from the Change Stream:");

    // Create the change stream cursor.
    MongoChangeStreamCursor<ChangeStreamDocument<Document>> cursor = collection.watch().cursor();

    // Insert a test document into the collection.
    collection.insertOne(Document.parse("{username: 'alice123', name: 'Alice'}"));
    ChangeStreamDocument<Document> next = cursor.next();
    System.out.println(next);
    cursor.close();
    sleep();

    /*
     * Example 2
     * Create a change stream with 'lookup' option enabled.
     * The test document will be returned with a full version of the updated document.
     */
    System.out.println("2. Document from the Change Stream, with lookup enabled:");

    // Create the change stream cursor.
    cursor = collection.watch().fullDocument(FullDocument.UPDATE_LOOKUP).cursor();

    // Update the test document.
    collection.updateOne(Document.parse("{username: 'alice123'}"),
            Document.parse("{$set : { email: 'alice@example.com'}}"));

    // Block until the next result is returned
    next = cursor.next();
    System.out.println(next);
    cursor.close();
    sleep();

    /*
     * Example 3
     * Create a change stream with 'lookup' option using a $match and ($redact or $project) stage.
     */
    System.out.println(
            "3. Document from the Change Stream, with lookup enabled, matching `update` operations only: ");

    // Insert some dummy data.
    collection.insertMany(asList(Document.parse("{updateMe: 1}"), Document.parse("{replaceMe: 1}")));

    // Create $match pipeline stage.
    List<Bson> pipeline = singletonList(
            Aggregates.match(Filters.or(Document.parse("{'fullDocument.username': 'alice123'}"),
                    Filters.in("operationType", asList("update", "replace", "delete")))));

    // Create the change stream cursor with $match.
    cursor = collection.watch(pipeline).fullDocument(FullDocument.UPDATE_LOOKUP).cursor();

    // Forward to the end of the change stream
    next = cursor.tryNext();

    // Update the test document.
    collection.updateOne(Filters.eq("updateMe", 1), Updates.set("updated", true));
    next = cursor.next();
    System.out.println(format("Update operationType: %s %n %s", next.getUpdateDescription(), next));

    // Replace the test document.
    collection.replaceOne(Filters.eq("replaceMe", 1), Document.parse("{replaced: true}"));
    next = cursor.next();
    System.out.println(format("Replace operationType: %s", next));

    // Delete the test document.
    collection.deleteOne(Filters.eq("username", "alice123"));
    next = cursor.next();
    System.out.println(format("Delete operationType: %s", next));
    cursor.close();
    sleep();

    /**
     * Example 4
     * Resume a change stream using a resume token.
     */
    System.out.println("4. Document from the Change Stream including a resume token:");

    // Get the resume token from the last document we saw in the previous change stream cursor.
    BsonDocument resumeToken = cursor.getResumeToken();
    System.out.println(resumeToken);

    // Pass the resume token to the resume after function to continue the change stream cursor.
    cursor = collection.watch().resumeAfter(resumeToken).cursor();

    // Insert a test document.
    collection.insertOne(Document.parse("{test: 'd'}"));

    // Block until the next result is returned
    next = cursor.next();
    System.out.println(next);
    cursor.close();
}

From source file:io.lumeer.storage.mongodb.dao.collection.MongoDataDao.java

License:Open Source License

private Bson createFilter(String collectionId, SearchQuery query) {
    List<Bson> filters = new ArrayList<>();
    // does not work as expected - cannot search for a single character for example, only whole words
    if (query.isFulltextQuery()) {

        Collection collection = collectionDao.getCollectionById(collectionId);
        List<Attribute> fulltextAttrs = collection.getAttributes().stream()
                .filter(attr -> attr.getName().toLowerCase().contains(query.getFulltext().toLowerCase()))
                .collect(Collectors.toList());

        // we only search by presence of the matching attributes
        if (fulltextAttrs.size() > 0) {
            filters.add(Filters.or(fulltextAttrs.stream().map(attr -> Filters.exists(attr.getId()))
                    .collect(Collectors.toList())));
        } else if (collection.getAttributes().size() > 0) { // we search by content
            filters.add(Filters.or(collection.getAttributes().stream()
                    .map(attr -> Filters.regex(attr.getId(), query.getFulltext(), "i"))
                    .collect(Collectors.toList())));
        }//from w w w  .j  av  a 2 s. c  o  m
    }
    if (query.isDocumentIdsQuery()) {
        List<ObjectId> ids = query.getDocumentIds().stream().filter(ObjectId::isValid).map(ObjectId::new)
                .collect(Collectors.toList());
        if (!ids.isEmpty()) {
            filters.add(Filters.in(ID, ids));
        }
    }
    if (query.isFiltersQuery()) {
        List<Bson> attributeFilters = query.getFilters().stream().map(this::attributeFilter)
                .filter(Objects::nonNull).collect(Collectors.toList());
        filters.addAll(attributeFilters);
    }

    final Bson result = filters.size() > 0 ? Filters.and(filters) : new Document();
    return result;
}

From source file:io.lumeer.storage.mongodb.dao.project.MongoViewDao.java

License:Open Source License

private static Bson viewSearchFilter(SearchQuery query) {
    List<Bson> filters = new ArrayList<>();
    if (query.isCollectionIdsQuery()) {
        filters.add(Filters.in(MongoUtils.concatParams(ViewCodec.QUERY, QueryCodec.COLLECTION_IDS),
                query.getCollectionIds()));
    }/*from w  w w.j a va  2s. c o  m*/
    if (query.isFulltextQuery()) {
        filters.add(
                Filters.regex(ViewCodec.NAME, Pattern.compile(query.getFulltext(), Pattern.CASE_INSENSITIVE)));
    }
    filters.add(MongoFilters.permissionsFilter(query));

    return Filters.and(filters);
}

From source file:io.lumeer.storage.mongodb.util.MongoFilters.java

License:Open Source License

private static Bson entityRolesFilter(Role role) {
    return Filters.in(PermissionCodec.ROLES, role.toString());
}

From source file:io.mandrel.cluster.node.impl.MongoNodeRepository.java

License:Apache License

@Override
public Collection<Node> findAll(Collection<String> ids) {
    return Lists.newArrayList(collection.find(Filters.in("_id", ids)).map(doc -> {
        try {/*  w w  w  .  ja v a2  s  . c om*/
            return mapper.readValue(doc.toJson(), Node.class);
        } catch (Exception e) {
            throw Throwables.propagate(e);
        }
    }));
}

From source file:io.mandrel.metadata.impl.MongoMetadataStore.java

License:Apache License

@Override
public Set<Uri> deduplicate(Collection<Uri> uris) {
    Set<Uri> temp = Sets.newHashSet(uris);

    Set<Uri> founds = Sets.newHashSet(collection.find(Filters.in("_id", uris))
            .projection(Projections.include("_id")).map(doc -> Uri.create(doc.getString("_id"))).iterator());
    temp.removeAll(founds);/*w w  w. j ava 2  s. c om*/

    return temp;
}

From source file:io.sip3.tapir.twig.mongo.query.SipSessionQuery.java

License:Apache License

@Override
public Bson filter() {
    return Filters.and(between(), Filters.in("call_id", callIds));
}