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

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

Introduction

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

Prototype

public static <TItem> Bson eq(final String fieldName, @Nullable final TItem value) 

Source Link

Document

Creates a filter that matches all documents where the value of the field name equals the specified value.

Usage

From source file:org.jooby.mongodb.MongoSessionStore.java

License:Apache License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*  w  ww  .  j  a v a 2  s . co  m*/
public Session get(final Builder builder) {
    return Optional.ofNullable(sessions.find(Filters.eq("_id", builder.sessionId())).first()).map(doc -> {
        Map session = new LinkedHashMap<>(doc);

        Date accessedAt = (Date) session.remove("_accessedAt");
        Date createdAt = (Date) session.remove("_createdAt");
        Date savedAt = (Date) session.remove("_savedAt");
        session.remove("_id");

        builder.accessedAt(accessedAt.getTime()).createdAt(createdAt.getTime()).savedAt(savedAt.getTime());
        session.forEach((k, v) -> builder.set(decode(k.toString()), v.toString()));
        return builder.build();
    }).orElse(null);
}

From source file:org.jooby.mongodb.MongoSessionStore.java

License:Apache License

@Override
public void save(final Session session) {
    syncTtl();//ww  w .  j ava 2 s. c  o m

    String id = session.id();
    Bson filter = Filters.eq("_id", id);

    Document doc = new Document().append("_id", id).append("_accessedAt", new Date(session.accessedAt()))
            .append("_createdAt", new Date(session.createdAt()))
            .append("_savedAt", new Date(session.savedAt()));
    // dump attributes
    Map<String, String> attributes = session.attributes();
    attributes.forEach((k, v) -> doc.append(encode(k), v));

    sessions.updateOne(filter, new Document("$set", doc), new UpdateOptions().upsert(true));
}

From source file:org.kaaproject.kaa.server.datamigration.CtlNotificationMigration.java

License:Apache License

@Override
protected List<Schema> transform() throws SQLException {
    List<Schema> res = super.transform();

    if (nosql.equals(Options.DEFAULT_NO_SQL)) {
        MongoDatabase database = client.getDatabase(dbName);
        MongoCollection<Document> notification = database.getCollection("notification");
        MongoCollection<Document> enpNotification = database.getCollection("endpoint_notification");

        FindIterable<Document> cursor = notification.find();
        for (Document document : cursor) {
            Object id = document.get("_id");
            Long schemaId = parseLong((String) document.get("notification_schema_id"));
            notification.updateMany(Filters.eq("_id", id),
                    Filters.eq("$set", Filters.eq("notification_schema_id", schemaId + idShift)));
        }/*from ww w  . jav a 2s. com*/

        cursor = enpNotification.find();
        for (Document document : cursor) {
            Object id = document.get("_id");
            Long schemaId = parseLong((String) document.get("notification.notification_schema_id"));
            notification.updateMany(Filters.eq("_id", id),
                    Filters.eq("$set", Filters.eq("notification.notification_schema_id", schemaId + idShift)));
        }
    } else {
        Session session = cluster.connect(dbName);
        BatchStatement batchStatement = new BatchStatement();

        //notification
        ResultSet results = session.execute(select().from("notification"));
        for (Row row : results) {
            String id = row.getString("nf_id");
            Long schemaId = parseLong(row.getString("schema_id"));
            String[] ids = id.split("::");

            batchStatement.add(update("notification").with(set("schema_id", String.valueOf(schemaId + idShift)))
                    .where(eq("topic_id", ids[0])).and(eq("nf_type", ids[1]))
                    .and(eq("nf_version", Integer.valueOf(ids[2])))
                    .and(eq("seq_num", Integer.valueOf(ids[3]))));
        }

        //endpoint notification
        results = session.execute(select().from("ep_nfs"));
        for (Row row : results) {
            String id = row.getString("nf_id");
            Long schemaId = parseLong(row.getString("schema_id"));
            String[] ids = id.split("::");
            ByteBuffer epKeyHash = Bytes.fromHexString(ids[0]);
            Date lastModTime = new Date(Long.valueOf(ids[1]));

            batchStatement.add(update("ep_nfs").with(set("schema_id", String.valueOf(schemaId + idShift)))
                    .where(eq("ep_key_hash", epKeyHash)).and(eq("last_mod_time", lastModTime)));
        }

        session.execute(batchStatement);
        session.close();
        cluster.close();
    }
    return res;
}

From source file:org.kaaproject.kaa.server.datamigration.UpdateUuidsMigration.java

License:Apache License

/**
 * Change encoding of uuids from Latin1 to Base64 in relational and NoSQL databases.
 *
 *//*  w  w w.ja va 2s  .c  o m*/
public void transform() throws IOException, SQLException {
    QueryRunner run = new QueryRunner();
    ResultSetHandler<List<Configuration>> rsHandler = new BeanListHandler<>(Configuration.class);
    List<Configuration> configs = run.query(connection, "SELECT * FROM configuration", rsHandler);
    for (Configuration config : configs) {
        JsonNode json = new ObjectMapper().readTree(config.getConfigurationBody());
        JsonNode jsonEncoded = encodeUuids(json);
        byte[] encodedConfigurationBody = jsonEncoded.toString().getBytes();

        int updates = run.update(connection, "UPDATE configuration SET configuration_body=? WHERE id=?",
                encodedConfigurationBody, config.getId());
        if (updates != 1) {
            System.err.println("Error: failed to update configuration: " + config);
        }
    }

    if (nosql.equals(Options.DEFAULT_NO_SQL)) {
        MongoDatabase database = client.getDatabase(dbName);
        MongoCollection<Document> userConfiguration = database.getCollection("user_configuration");
        FindIterable<Document> documents = userConfiguration.find();
        for (Document d : documents) {
            String body = (String) d.get("body");
            JsonNode json = new ObjectMapper().readTree(body);
            JsonNode jsonEncoded = encodeUuids(json);
            userConfiguration.updateOne(Filters.eq("_id", d.get("_id")),
                    Filters.eq("$set", Filters.eq("body", jsonEncoded)));
        }

    } else {
        Session session = cluster.connect(dbName);
        BatchStatement batchStatement = new BatchStatement();

        String tableName = "user_conf";
        ResultSet results = session.execute(select().from(tableName));
        for (Row row : results) {
            String userId = row.getString("user_id");
            String appToken = row.getString("app_token");
            int schemaVersion = row.getInt("schema_version");

            String body = row.getString("body");
            String bodyEncoded = encodeUuids(new ObjectMapper().readTree(body)).toString();

            batchStatement.add(update(tableName).with(set("body", bodyEncoded)).where(eq("user_id", userId))
                    .and(eq("app_token", appToken)).and(eq("schema_version", schemaVersion)));
        }

        session.execute(batchStatement);
        session.close();
        cluster.close();
    }

}

From source file:org.netbeans.modules.mongodb.ui.components.result_panel.actions.EditBsonPropertyNodeAction.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent e) {
    BsonProperty property = propertyNode.getBsonProperty();
    BsonProperty newProperty = BsonPropertyEditor.show(property);
    if (newProperty == null) {
        return;//from  w  ww. j a v  a 2 s  .c o  m
    }
    propertyNode.setPropertyName(newProperty.getName());
    getResultPanel().getTreeTableModel().setUserObject(propertyNode, newProperty.getValue());
    TreeTableNode parentNode = propertyNode.getParent();
    BsonDocument document = (BsonDocument) parentNode.getUserObject();
    if (newProperty.getName().equals(property.getName()) == false) {
        document.remove(property.getName());
    }
    document.put(newProperty.getName(), newProperty.getValue());
    while ((parentNode.getParent() instanceof RootNode) == false) {
        parentNode = parentNode.getParent();
    }
    try {
        final MongoCollection<BsonDocument> collection = getResultPanel().getLookup()
                .lookup(MongoCollection.class);
        collection.replaceOne(Filters.eq("_id", document.get("_id")), document);

    } catch (MongoException ex) {
        DialogNotification.error(ex);
    }
}

From source file:org.oddcyb.atoms.store.MongoDBStore.java

License:Apache License

@Override
public Object read(String name) {
    Document result = this.collection.find(Filters.eq(NAME_ENTRY, name)).first();

    return (result != null) ? result.get(OBJECT_ENTRY) : null;
}

From source file:org.oddcyb.atoms.store.MongoDBStore.java

License:Apache License

@Override
public Object replace(String name, Object newValue) {
    Object existing = this.read(name);
    if (existing == null) {
        return null;
    }//from  w  w w.  jav  a2s  .c o  m

    this.collection.updateOne(Filters.eq(NAME_ENTRY, name),
            new Document("$SET", new Document(OBJECT_ENTRY, newValue)));

    return existing;
}

From source file:org.oddcyb.atoms.store.MongoDBStore.java

License:Apache License

@Override
public Object delete(String name) {
    Object existing = this.read(name);

    this.collection.deleteOne(Filters.eq(NAME_ENTRY, name));

    return existing;
}

From source file:org.opencb.cellbase.lib.impl.ClinicalMongoDBAdaptor.java

License:Apache License

private void getGwasFilters(Query query, Set<String> sourceContent, List<Bson> sourceBson) {
    // If only clinvar-specific filters are provided it must be avoided to include the source=gwas condition since
    // sourceBson is going to be an OR list
    if (!(query.containsKey(QueryParams.CLINVARRCV.key()) || query.containsKey(QueryParams.CLINVARCLINSIG.key())
            || query.containsKey(QueryParams.CLINVARREVIEW.key())
            || query.containsKey(QueryParams.CLINVARTYPE.key())
            || query.containsKey(QueryParams.CLINVARRS.key()))) {
        if (sourceContent != null && sourceContent.contains("gwas")) {
            sourceBson.add(Filters.eq("source", "gwas"));
        }/*from w w w.ja v  a  2  s.  com*/
    }
}

From source file:org.opencb.cellbase.lib.impl.ClinicalMongoDBAdaptor.java

License:Apache License

private void getCosmicFilters(Query query, Set<String> sourceContent, List<Bson> sourceBson) {
    // If only clinvar-specific filters are provided it must be avoided to include the source=cosmic condition since
    // sourceBson is going to be an OR list
    List<Bson> andBson = new ArrayList<>();
    if (!(query.containsKey(QueryParams.CLINVARRCV.key()) || query.containsKey(QueryParams.CLINVARCLINSIG.key())
            || query.containsKey(QueryParams.CLINVARREVIEW.key())
            || query.containsKey(QueryParams.CLINVARTYPE.key())
            || query.containsKey(QueryParams.CLINVARRS.key()))) {
        if (sourceContent != null && sourceContent.contains("cosmic")) {
            andBson.add(Filters.eq("source", "cosmic"));
        }/*  w  w  w.  j  a v a 2 s.co m*/

        createOrQuery(query, QueryParams.COSMICID.key(), "mutationID", andBson);
        if (andBson.size() == 1) {
            sourceBson.add(andBson.get(0));
        } else if (andBson.size() > 0) {
            sourceBson.add(Filters.and(andBson));
        }
    }
}