Example usage for com.mongodb.client MongoCollection find

List of usage examples for com.mongodb.client MongoCollection find

Introduction

In this page you can find the example usage for com.mongodb.client MongoCollection find.

Prototype

FindIterable<TDocument> find();

Source Link

Document

Finds all documents in the collection.

Usage

From source file:org.hillview.storage.MongoDBLoader.java

License:Open Source License

public ITable load(int offset, int count) {
    MongoCollection<Document> collection = this.database.getCollection(info.table);
    Iterable<Document> cursor = collection.find().skip(offset).limit(count);

    // This is not the most efficient way to do things, but it is simple
    Iterable<JsonElement> data = Linq.map(cursor, MongoDBLoader::convert);

    Schema schema = this.guessSchema(filename, data.iterator());
    IAppendableColumn[] columns = schema.createAppendableColumns();

    int currentRow = 0;
    // reopen the iterator
    for (JsonElement e : Linq.map(cursor, MongoDBLoader::convert))
        this.append(columns, e);
    ITable table = new Table(columns, this.info.table, null);
    this.close(null);
    return table;
}

From source file:org.iotivity.cloud.accountserver.db.MongoDB.java

License:Open Source License

private void showRecord(String tableName) {

    MongoCollection<Document> collection = db.getCollection(tableName);
    MongoCursor<Document> cursor = collection.find().iterator();

    Log.i("<" + tableName + ">");

    HashMap<String, Object> records = null;
    int index = 0;
    while (cursor.hasNext()) {

        Document doc = cursor.next();
        records = convertDocumentToHashMap(doc);

        Log.i("[" + index + "] " + records.toString());
        index++;//from  w w w  .  jav  a  2 s  . c  o m
    }

    cursor.close();
}

From source file:org.jaqpot.core.db.entitymanager.MongoDBEntityManager.java

License:Open Source License

@Override
public <T extends JaqpotEntity> List<T> findAll(Class<T> entityClass, Integer start, Integer max) {
    MongoDatabase db = mongoClient.getDatabase(database);
    MongoCollection<Document> collection = db.getCollection(collectionNames.get(entityClass));
    List<T> result = new ArrayList<>();
    collection.find().skip(start != null ? start : 0).limit(max != null ? max : DEFAULT_PAGE_SIZE)
            .map(document -> serializer.parse(JSON.serialize(document), entityClass)).into(result);
    return result;
}

From source file:org.jaqpot.core.db.entitymanager.MongoDBEntityManager.java

License:Open Source License

@Override
public <T extends JaqpotEntity> List<T> findAll(Class<T> entityClass, List<String> fields, Integer start,
        Integer max) {//from  w  w w. j  a v a 2  s  . c  om
    MongoDatabase db = mongoClient.getDatabase(database);
    MongoCollection<Document> collection = db.getCollection(collectionNames.get(entityClass));
    List<T> result = new ArrayList<>();
    Document filter = new Document();
    fields.stream().forEach(f -> filter.put(f, 1));
    collection.find().projection(filter).skip(start != null ? start : 0)
            .limit(max != null ? max : DEFAULT_PAGE_SIZE)
            .map(document -> serializer.parse(JSON.serialize(document), entityClass)).into(result);
    return result;
}

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  w  w w.j  av  a 2  s .  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.
 *
 *///from   www  .  ja  v  a2  s .c  om
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.lambda3.indra.mongo.MongoVectorSpace.java

License:Open Source License

@Override
protected ModelMetadata loadMetadata() {
    MongoDatabase db = this.mongoClient.getDatabase(dbName);
    MongoCollection<Document> metadataColl = db.getCollection(METADATA_COLL_NAME);
    //TODO metadata needs to include CM

    if (metadataColl.count() > 1) {
        throw new IndraRuntimeException(
                "This model is misconfigured. Contact the support with the following message: model metadata has more than one entry.");
    }//from   w  w w.ja  va 2  s .com

    if (metadataColl.count() == 1) {
        logger.debug("Using stored metadata of {}", dbName);
        Document storedMetadata = metadataColl.find().first();
        return new ModelMetadata(storedMetadata);
    } else {
        logger.debug("No metadata found in {}, using defaults.", dbName);
        //TODO throws an exception.
        //no default supported anymore.
        return null;
    }
}