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(ClientSession clientSession);

Source Link

Document

Finds all documents in the collection.

Usage

From source file:com.centurylink.mdw.dataaccess.db.CommonDataAccess.java

License:Apache License

public Document loadDocument(Long documentId, boolean forUpdate) throws SQLException {
    String query = "select CREATE_DT, MODIFY_DT, DOCUMENT_TYPE, OWNER_TYPE, OWNER_ID "
            + "from DOCUMENT where DOCUMENT_ID = ?" + (forUpdate ? " for update" : "");
    ResultSet rs = db.runSelect(query, documentId);
    if (rs.next()) {
        Document vo = new Document();
        vo.setDocumentId(documentId);//w  w  w. j  ava 2  s  .  co m
        vo.setCreateDate(rs.getTimestamp("CREATE_DT"));
        vo.setModifyDate(rs.getTimestamp("MODIFY_DT"));
        vo.setDocumentType(rs.getString("DOCUMENT_TYPE"));
        vo.setOwnerType(rs.getString("OWNER_TYPE"));
        vo.setOwnerId(rs.getLong("OWNER_ID"));
        boolean foundInMongo = false;
        if (DatabaseAccess.getMongoDb() != null) {
            CodeTimer timer = new CodeTimer("Load mongodb doc", true);
            MongoCollection<org.bson.Document> mongoCollection = DatabaseAccess.getMongoDb()
                    .getCollection(vo.getOwnerType());
            org.bson.Document mongoQuery = new org.bson.Document("_id", vo.getDocumentId());
            org.bson.Document c = mongoCollection.find(mongoQuery).limit(1)
                    .projection(fields(include("CONTENT", "isJSON"), excludeId())).first();
            if (c != null) {
                if (c.getBoolean("isJSON", false))
                    vo.setContent(DatabaseAccess.decodeMongoDoc(c.get("CONTENT", org.bson.Document.class))
                            .toJson(new JsonWriterSettings(true)));
                else
                    vo.setContent(c.getString("CONTENT"));
                foundInMongo = true;
            }
            timer.stopAndLogTiming(null);
        }
        if (!foundInMongo) {
            query = "select CONTENT from DOCUMENT_CONTENT where DOCUMENT_ID = ?";
            rs = db.runSelect(query, documentId);
            if (rs.next())
                vo.setContent(rs.getString("CONTENT"));
        }
        return vo;
    } else {
        throw new SQLException("Document with ID " + documentId + " does not exist");
    }
}

From source file:com.centurylink.mdw.mongo.MongoDocumentDb.java

License:Apache License

@Override
public String getDocumentContent(String ownerType, Long documentId) {
    CodeTimer timer = new CodeTimer("Load from documentDb", true);
    try {/*from   w ww.j  av  a2  s  .c om*/
        MongoCollection<org.bson.Document> mongoCollection = getMongoDb().getCollection(ownerType);
        org.bson.Document mongoQuery = new org.bson.Document("document_id", documentId);
        org.bson.Document c = mongoCollection.find(mongoQuery).limit(1)
                .projection(fields(include("CONTENT", "isJSON"), excludeId())).first();
        if (c == null) {
            return null;
        } else if (c.getBoolean("isJSON", false)) {
            return decodeMongoDoc(c.get("CONTENT", org.bson.Document.class))
                    .toJson(JsonWriterSettings.builder().indent(true).build());
        } else {
            return c.getString("CONTENT");
        }
    } finally {
        timer.stopAndLogTiming(null);
    }
}

From source file:com.centurylink.mdw.service.data.RequestDataAccess.java

License:Apache License

public Request getRequest(Long id, boolean withContent, boolean withResponseContent)
        throws DataAccessException {
    try {//from   w  w w  .  jav  a 2s  .  co  m
        String query = "select create_dt, owner_type, owner_id";
        query += " from document where document_id = ?";
        db.openConnection();
        ResultSet rs = db.runSelect(query, id);
        Request request = null;
        String ownerType = null;
        Long ownerId = null;
        if (rs.next()) {
            request = new Request(id);
            request.setCreated(rs.getTimestamp("create_dt"));
            ownerType = rs.getString("owner_type");
            ownerId = rs.getLong("owner_id");
            if (withContent) {
                boolean foundInMongo = false;
                if (DatabaseAccess.getMongoDb() != null) {
                    CodeTimer timer = new CodeTimer("Load mongodb doc", true);
                    MongoCollection<org.bson.Document> mongoCollection = DatabaseAccess.getMongoDb()
                            .getCollection(ownerType);
                    org.bson.Document mongoQuery = new org.bson.Document("_id", id);
                    org.bson.Document c = mongoCollection.find(mongoQuery).limit(1)
                            .projection(fields(include("CONTENT", "isJSON"), excludeId())).first();
                    if (c != null) {
                        if (c.getBoolean("isJSON", false))
                            request.setContent(
                                    DatabaseAccess.decodeMongoDoc(c.get("CONTENT", org.bson.Document.class))
                                            .toJson(new JsonWriterSettings(true)));
                        else
                            request.setContent(c.getString("CONTENT"));
                        foundInMongo = true;
                    }
                    timer.stopAndLogTiming(null);
                }
                if (!foundInMongo) {
                    query = "select content from document_content where document_id = ?";
                    rs = db.runSelect(query, id);
                    if (rs.next())
                        request.setContent(rs.getString("content"));
                }
            }
        } else {
            return null;
        }

        ResultSet responseRs = null;
        String responseQuery = "select document_id, create_dt, status_code, status_message";
        String responseOwnerType = null;
        if (OwnerType.ADAPTER_REQUEST.equals(ownerType) && ownerId != null) {
            responseOwnerType = OwnerType.ADAPTER_RESPONSE;
            request.setOutbound(true);
            responseQuery += " from document where owner_type='" + responseOwnerType + "' and owner_id = ?";
            responseRs = db.runSelect(responseQuery, ownerId);
        } else if (OwnerType.LISTENER_REQUEST.equals(ownerType)) {
            responseOwnerType = OwnerType.LISTENER_RESPONSE;
            responseQuery += " from document where owner_type='" + responseOwnerType + "' and owner_id = ?";
            responseRs = db.runSelect(responseQuery, ownerId);
        }
        if (responseRs != null && responseRs.next()) {
            request.setResponseId(responseRs.getLong("document_id"));
            request.setResponded(responseRs.getTimestamp("create_dt"));
            request.setStatusCode(responseRs.getInt("status_code"));
            request.setStatusMessage(responseRs.getString("status_message"));

            if (withResponseContent) {
                boolean foundInMongo = false;
                if (DatabaseAccess.getMongoDb() != null) {
                    CodeTimer timer = new CodeTimer("Load mongodb doc", true);
                    MongoCollection<org.bson.Document> mongoCollection = DatabaseAccess.getMongoDb()
                            .getCollection(responseOwnerType);
                    org.bson.Document mongoQuery = new org.bson.Document("_id", request.getResponseId());
                    org.bson.Document c = mongoCollection.find(mongoQuery).limit(1)
                            .projection(fields(include("CONTENT", "isJSON"), excludeId())).first();
                    if (c != null) {
                        if (c.getBoolean("isJSON", false))
                            request.setContent(c.get("CONTENT", org.bson.Document.class)
                                    .toJson(new JsonWriterSettings(true)));
                        else
                            request.setContent(c.getString("CONTENT"));
                        foundInMongo = true;
                    }
                    timer.stopAndLogTiming(null);
                }
                if (!foundInMongo) {
                    query = "select content from document_content where document_id = ?";
                    responseRs = db.runSelect(query, request.getResponseId());
                    if (responseRs.next())
                        request.setResponseContent(responseRs.getString("content"));
                }
            }
        }

        return request;
    } catch (Exception ex) {
        throw new DataAccessException("Failed to retrieve requestId: ", ex);
    } finally {
        db.closeConnection();
    }
}

From source file:com.chadcover.Homework_23.java

License:Apache License

public static void main(String[] args) {
    MongoClient client = new MongoClient();
    MongoDatabase database = client.getDatabase("students");
    MongoCollection<Document> collection = database.getCollection("gradesBak");

    long count = collection.count();
    System.out.println(count);//w w  w . j  a v  a 2 s  . com

    Bson filter = eq("type", "homework");
    Bson sort = ascending("student_id", "score");
    Bson projection = fields(include("student_id", "score"));

    // better for large datasets
    MongoCursor<Document> result = collection.find(filter).sort(sort).projection(projection).iterator();
    try {
        int lastId = 0;
        int counter = 0;
        while (result.hasNext()) {
            Document cur = result.next();
            int id = (Integer) cur.get("student_id");
            // when moving to new student
            // delete that record, which is the lowest homework score
            if (id != lastId || counter == 0) {
                double grade = (Double) cur.get("score");
                System.out.println("Delete this score: " + grade);
                collection.deleteOne(eq("_id", cur.get("_id")));
            } else {
                // do nothing
            }
            lastId = id;
            counter++;
        }
    } finally {
        result.close();
    }

}

From source file:com.cognifide.aet.vs.metadata.MetadataDAOMongoDBImpl.java

License:Apache License

@Override
public Suite getSuite(DBKey dbKey, String correlationId) throws StorageException {
    Suite suite = null;/*from   w w  w  .ja v  a  2 s .c  o  m*/
    MongoCollection<Document> metadata = getMetadataCollection(dbKey);

    LOGGER.debug("Fetching suite with correlationId: {} ", correlationId);

    final FindIterable<Document> found = metadata.find(Filters.eq(CORRELATION_ID_PARAM_NAME, correlationId))
            .sort(Sorts.descending(SUITE_VERSION_PARAM_NAME)).limit(1);
    final Document result = found.first();
    if (result != null) {
        suite = GSON.fromJson(result.toJson(), SUITE_TYPE);
    }

    return suite;
}

From source file:com.cognifide.aet.vs.metadata.MetadataDAOMongoDBImpl.java

License:Apache License

@Override
public Suite getLatestRun(DBKey dbKey, String name) throws StorageException {
    Suite suite = null;/*from  w  ww  .  j a v  a2  s. c  o  m*/
    MongoCollection<Document> metadata = getMetadataCollection(dbKey);
    LOGGER.debug("Fetching latest suite run for company: `{}`, project: `{}`, name `{}`.", dbKey.getCompany(),
            dbKey.getProject(), name);

    final FindIterable<Document> found = metadata.find(Filters.eq("name", name))
            .sort(Sorts.descending(SUITE_VERSION_PARAM_NAME)).limit(1);
    final Document result = found.first();
    if (result != null) {
        suite = GSON.fromJson(result.toJson(), SUITE_TYPE);
    }

    return suite;
}

From source file:com.cognitive.cds.invocation.mongo.EngineInfoDao.java

License:Apache License

/**
 * Call the server to fetch the engine//from ww w .  jav  a  2 s . c  o m
 *
 * @param name
 * @return
 */
protected EngineInfo fetchEngine(String name) {
    EngineInfo engine = null;

    mongoDbDao.setDatabase("engine");
    MongoCollection<Document> collection = mongoDbDao.getCollection("engines");
    logger.info("Engines Count: " + collection.count());

    Document filter = new Document();
    filter.put("name", name);
    Document eng = collection.find(filter).first();

    if (eng != null) {
        try {
            String json = eng.toJson();
            engine = (EngineInfo) JsonUtils.getMapper().readValue(json, EngineInfo.class);
            engine.setId(engine.get_id().toHexString());

        } catch (IOException e) {
            logger.error("========> Deserialize: " + e.toString());
        }
    }
    return engine;
}

From source file:com.cognitive.cds.invocation.mongo.EngineInfoDao.java

License:Apache License

public ArrayList<EngineInstanceState> getActiveEngines(String type) {

    ArrayList<EngineInstanceState> engines = new ArrayList<EngineInstanceState>();
    mongoDbDao.setDatabase("engine");
    MongoCollection<Document> collection = mongoDbDao.getCollection("instance");
    logger.debug("Total engine instance count: " + collection.count());

    Document filter = new Document();
    filter.put("type", type);
    filter.put("status", true);
    FindIterable<Document> actives = collection.find(filter);
    for (Document document : actives) {
        try {/*from w  w w .  jav  a  2s . c o  m*/
            String json = document.toJson();
            EngineInstanceState eng = (EngineInstanceState) JsonUtils.getMapper().readValue(json,
                    EngineInstanceState.class);
            engines.add(eng);
        } catch (Exception e) {
            logger.error("=======> EngineState - intentMapping Insert Exception EngineState: " + e.toString());
        }
    }
    logger.debug("Total active engine instance count: " + engines.size() + " of type: " + type);
    return engines;
}

From source file:com.cognitive.cds.invocation.mongo.IntentMappingDao.java

License:Apache License

public IntentMapping getIntent(String intentName) {
    IntentMapping im = null;/*from w  ww.  j a  v  a  2  s  .  c o m*/

    if (cache.containsKey(intentName)) {
        return cache.get(intentName);
    }

    mongoDbDao.setDatabase("intent");
    MongoCollection<Document> collection = mongoDbDao.getCollection("cdsintent");

    Document filter = new Document();
    filter.put("name", intentName);

    Document obj = collection.find(filter).first();

    if (obj != null) {
        try {
            String json = obj.toJson();
            im = mapper.readValue(json, IntentMapping.class);
            im.setId(im.get_id().toHexString());
        } catch (IOException e) {
            logger.error("========> Deserialize: " + e.toString());
        }
    }
    if (cacheIntents == true && im != null) {
        cache.put(intentName, im);
    }
    return im;
}

From source file:com.cognitive.cds.invocation.mongo.IntentMappingDao.java

License:Apache License

public Document updateIntentMapping(IntentMapping im) throws JsonProcessingException {
    MongoClient mongo = mongoDbDao.getMongoClient();
    MongoDatabase db = mongo.getDatabase("intent");
    MongoCollection<Document> collection = db.getCollection("cdsintent");

    Document filter = new Document();
    if (im.get_id() != null) {
        filter.put("_id", im.get_id());
    } else if (im.getId() != null && !im.getId().isEmpty()) {
        filter.put("_id", new ObjectId(im.getId()));
    } else {//from   ww w. j ava2 s.  co m
        return null;
    }
    Document obj = collection.find(filter).first();
    Document result = null;

    if (obj != null) {
        try {
            String objectJson = mapper.writeValueAsString(im);
            Document doc = Document.parse(objectJson);
            doc.put("_id", im.get_id());

            result = collection.findOneAndReplace(filter, doc);
            if (cache.containsKey(im.getName())) {
                cache.put(im.getName(), im);
            }

        } catch (IOException e) {
            logger.error("========> Deserialize: " + e.toString());
        }
    }
    return result;
}