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

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

Introduction

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

Prototype


public static Bson exists(final String fieldName, final boolean exists) 

Source Link

Document

Creates a filter that matches all documents that either contain or do not contain the given field, depending on the value of the exists parameter.

Usage

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

License:Apache License

@SuppressWarnings("unchecked")
@Override//from  w w w  .j a v  a 2 s  .  c om
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.px100systems.data.plugin.storage.mongo.FilterQueryBuilder.java

License:Open Source License

@Override
public Bson convert(Criteria.isNull predicate) {
    return Filters.exists(predicate.getMember(), false);
}

From source file:io.debezium.connector.mongodb.Replicator.java

License:Apache License

/**
 * Use the given primary to read the oplog.
 * //  w w w.  j  a  v a  2  s  .c  o m
 * @param primary the connection to the replica set's primary node; may not be null
 */
protected void readOplog(MongoClient primary) {
    BsonTimestamp oplogStart = source.lastOffsetTimestamp(replicaSet.replicaSetName());
    logger.info("Reading oplog for '{}' primary {} starting at {}", replicaSet, primary.getAddress(),
            oplogStart);

    // Include none of the cluster-internal operations and only those events since the previous timestamp ...
    MongoCollection<Document> oplog = primary.getDatabase("local").getCollection("oplog.rs");
    Bson filter = Filters.and(Filters.gt("ts", oplogStart), // start just after our last position
            Filters.exists("fromMigrate", false)); // skip internal movements across shards
    FindIterable<Document> results = oplog.find(filter).sort(new Document("$natural", 1)) // force forwards collection scan
            .oplogReplay(true) // tells Mongo to not rely on indexes
            .noCursorTimeout(true) // don't timeout waiting for events
            .cursorType(CursorType.TailableAwait); // tail and await new data
    // Read as much of the oplog as we can ...
    ServerAddress primaryAddress = primary.getAddress();
    try (MongoCursor<Document> cursor = results.iterator()) {
        while (running.get() && cursor.hasNext()) {
            if (!handleOplogEvent(primaryAddress, cursor.next())) {
                // Something happened, and we're supposed to stop reading
                return;
            }
        }
    }
}

From source file:org.nuxeo.directory.mongodb.MongoDBDirectory.java

License:Apache License

@Override
public Session getSession() throws DirectoryException {

    SchemaManager schemaManager = Framework.getService(SchemaManager.class);
    Schema schema = schemaManager.getSchema(getSchema());
    if (schema == null) {
        throw new DirectoryException(getSchema() + " is not a registered schema");
    }/*from  w  ww  .  j  a  v  a 2 s.c  om*/
    schemaFieldMap = new LinkedHashMap<>();
    schema.getFields().forEach(f -> schemaFieldMap.put(f.getName().getLocalName(), f));

    MongoDBSession session = new MongoDBSession(this);
    addSession(session);

    // Initialize counters collection if autoincrement enabled
    if (descriptor.isAutoincrementIdField() && !session.hasCollection(countersCollectionName)) {
        Map<String, Object> seq = new HashMap<>();
        seq.put(MONGODB_ID, getName());
        seq.put(MONGODB_SEQ, 0L);
        session.getCollection(countersCollectionName).insertOne(MongoDBSerializationHelper.fieldMapToBson(seq));
    }

    if (!initialized) {
        String policy = descriptor.getCreateTablePolicy();
        MongoCollection collection = session.getCollection(getName());
        boolean dropCollection = false;
        boolean loadData = false;

        switch (policy) {
        case CREATE_TABLE_POLICY_ALWAYS:
            dropCollection = true;
            loadData = true;
            break;
        case CREATE_TABLE_POLICY_ON_MISSING_COLUMNS:
            if (session.hasCollection(getName())) {
                long totalEntries = collection.count();
                boolean missingColumns = schema.getFields().stream().map(f -> f.getName().getLocalName())
                        .anyMatch(fname -> collection.count(Filters.exists(fname, false)) == totalEntries);
                if (missingColumns) {
                    dropCollection = true;
                    loadData = true;
                }
            } else {
                loadData = true;
            }
            break;
        default:
            if (!session.hasCollection(getName())) {
                loadData = true;
            }
            break;
        }
        if (dropCollection) {
            collection.drop();
        }
        if (loadData) {
            loadData(schema, session);
        }
        initialized = true;
    }
    return session;
}