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:org.piotr.apollo.service.LessonService.java

private List<Lesson> getLessonBySectionId(String sectionId) {

    List<Lesson> lessonList = new ArrayList<>();
    MongoCollection collection = mongoDB.getCollection(lessonCollection);

    Document doc = new Document();

    doc.append("section_Id", new ObjectId(sectionId));

    FindIterable findIterable = collection.find(doc);
    MongoCursor<Document> cursor = findIterable.iterator();

    while (cursor.hasNext()) {
        Document obj = cursor.next();
        Lesson lesson = new Lesson();
        ObjectId id = (ObjectId) obj.get("_id");

        lesson.set_Id(id);//from w  ww . jav a 2 s  .  co  m
        lesson.setId(id.toString());
        lesson.setCode(obj.getString("code"));
        lesson.setName(obj.getString("name"));
        lesson.setDescription(obj.getString("description"));
        lesson.setTestCounter(obj.getInteger("testCounter"));
        lesson.setPercentageCorrect(obj.getDouble("percentageCorrect"));
        lesson.setGrade(obj.getDouble("grade"));

        lessonList.add(lesson);
    }

    return lessonList;
}

From source file:org.piotr.apollo.service.LessonService.java

public void updateLessonTest(Finished finished) {

    MongoCollection collection = mongoDB.getCollection(lessonCollection);
    Double gradeToUpdate = 0.0;//from  w w  w .  j  av  a 2 s.c  o m

    BasicDBObject toUpdate = new BasicDBObject();
    BasicDBObject oldObject = new BasicDBObject();

    oldObject.append("_id", new ObjectId(finished.getLessonId()));

    Document document = new Document();
    document.append("_id", new ObjectId(finished.getLessonId()));

    FindIterable iterable = collection.find(document);
    MongoCursor<Document> cursor = iterable.iterator();

    while (cursor.hasNext()) {
        Document temp = cursor.next();

        Integer testCounter = temp.getInteger("testCounter");
        Double percentageCorrect = temp.getDouble("percentageCorrect");

        toUpdate.append("testCounter", testCounter + 1);

        if (percentageCorrect != 0.0) {
            toUpdate.append("percentageCorrect", (percentageCorrect + finished.getPercentage()) / 2);
            gradeToUpdate = getProperGrade((percentageCorrect + finished.getPercentage()) / 2);
        } else {
            toUpdate.append("percentageCorrect", finished.getPercentage());
            gradeToUpdate = getProperGrade(finished.getPercentage());
        }

        toUpdate.append("grade", gradeToUpdate);

        collection.updateOne(oldObject, new BasicDBObject("$set", toUpdate));

    }
}

From source file:org.piotr.apollo.service.QuestionService.java

public List<Question> getQuestion(ObjectId testId) {
    MongoCollection collection = db.getCollection(questionCollection);
    List<Question> questionList = new ArrayList<Question>();
    Document findQuestions = new Document();

    findQuestions.append("test_id", testId);

    FindIterable iterable = collection.find(findQuestions);
    MongoCursor<Document> cursor = iterable.iterator();

    while (cursor.hasNext()) {
        Document document = cursor.next();

        Question question = new Question();
        question.setTest_id(testId);/*from  w  ww. j  av  a 2 s.c  o m*/
        question.setId(document.get("_id").toString());
        question.set_Id((ObjectId) document.get("_id"));
        question.setQuestion(document.getString("question"));
        question.setNumber(document.getInteger("number"));

        List<Answer> answersList = answerService.getAnswers(question.get_Id());
        question.setAnswersList(answersList);
        questionList.add(question);
    }

    return questionList;
}

From source file:org.radarcns.mongo.util.MongoHelper.java

License:Apache License

/**
 * Finds all documents within a time window belonging to the given subject, source and project.
 * Close the returned iterator after use, for example with a try-with-resources construct.
 *
 * @param collection is the MongoDB that will be queried
 * @param projectName of the project/*from  w ww.  ja  v a 2 s  .  com*/
 * @param subjectId is the subjectID
 * @param sourceId is the sourceID
 * @param timeFrame the queried timewindow
 * @return a MongoDB cursor containing all documents from the query.
 */
public static MongoCursor<Document> findDocumentsBySource(MongoCollection<Document> collection,
        String projectName, String subjectId, String sourceId, TimeFrame timeFrame) {
    createIndexIfNotAvailable(collection, indexProjectSubjectSourceTimestart);
    Bson querySource = filterSource(projectName, subjectId, sourceId, timeFrame);
    BasicDBObject sortStartTime = new BasicDBObject(KEY + "." + START, ASCENDING);

    if (logger.isDebugEnabled()) {
        BsonDocument findQueryDocument = querySource.toBsonDocument(Document.class,
                collection.getCodecRegistry());
        logger.debug("Filtering query {} and sorting by {}", findQueryDocument, sortStartTime);
    }

    return collection.find(querySource).sort(sortStartTime).iterator();
}

From source file:org.radarcns.mongo.util.MongoHelper.java

License:Apache License

/**
 * Finds all documents belonging to the given subject, source and project.
 * Close the returned iterator after use, for example with a try-with-resources construct.
 *
 * @param collection MongoDB collection name that will be queried
 * @param project project name//  www .j  a v  a 2s . c  om
 * @param subject subject ID
 * @param source source ID
 * @param sortBy Field to sort by. If sortBy is {@code null}, the data will not be sorted.
 *               The field should be prefixed with {@link MongoHelper#KEY} or
 *               {@link MongoHelper#VALUE}.
 * @param order {@code 1} means ascending while {@code -1} means descending
 * @param limit is the number of document that will be retrieved. If the limit is {@code null},
 *              no limit is used.
 * @return a MongoDB cursor containing all documents from query.
 * @throws IllegalArgumentException if sortBy does not start with a key or value object.
 */
public static MongoCursor<Document> findDocumentBySource(MongoCollection<Document> collection, String project,
        String subject, String source, String sortBy, int order, Integer limit) {

    createIndexIfNotAvailable(collection, indexProjectSubjectSource);

    FindIterable<Document> result = collection.find(filterSource(project, subject, source));

    if (sortBy != null) {
        if (!sortBy.startsWith(KEY + ".") && !sortBy.startsWith(VALUE + ".")) {
            throw new IllegalArgumentException(
                    "Should sort by a MongoHelper.KEY or MongoHelper.VALUE property.");
        }
        result = result.sort(new BasicDBObject(sortBy, order));
    }
    if (limit != null) {
        result = result.limit(limit);
    }

    return result.iterator();
}

From source file:org.restheart.db.CollectionDAO.java

License:Open Source License

/**
 * Returs the FindIterable<BsonDocument> of the collection applying sorting,
 * filtering and projection.//w w  w .  java  2 s. c om
 *
 * @param sortBy the sort expression to use for sorting (prepend field name
 * with - for descending sorting)
 * @param filters the filters to apply.
 * @param keys the keys to return (projection)
 * @return
 * @throws JsonParseException
 */
FindIterable<BsonDocument> getFindIterable(final MongoCollection<BsonDocument> coll, final BsonDocument sortBy,
        final BsonDocument filters, final BsonDocument keys) throws JsonParseException {

    return coll.find(filters).projection(keys).sort(sortBy);
}

From source file:org.restheart.db.CollectionDAO.java

License:Open Source License

/**
 * Returns the collection properties document.
 *
 * @param dbName the database name of the collection
 * @param collName the collection name/*from w w  w.  j  a  v a  2s. c om*/
 * @return the collection properties document
 */
public BsonDocument getCollectionProps(final String dbName, final String collName) {
    MongoCollection<BsonDocument> propsColl = getCollection(dbName, "_properties");

    BsonDocument props = propsColl
            .find(new BsonDocument("_id", new BsonString("_properties.".concat(collName)))).limit(1).first();

    if (props != null) {
        props.append("_id", new BsonString(collName));
    } else if (doesCollectionExist(dbName, collName)) {
        return new BsonDocument("_id", new BsonString(collName));
    }

    return props;
}

From source file:org.restheart.db.CollectionDAO.java

License:Open Source License

/**
 * Upsert the collection properties./*from   ww  w. j  a v a2 s .  c  o  m*/
 *
 * @param dbName the database name of the collection
 * @param collName the collection name
 * @param properties the new collection properties
 * @param requestEtag the entity tag. must match to allow actual write if
 * checkEtag is true (otherwise http error code is returned)
 * @param updating true if updating existing document
 * @param patching true if use patch semantic (update only specified fields)
 * @param checkEtag true if etag must be checked
 * @return the HttpStatus code to set in the http response
 */
@SuppressWarnings("unchecked")
OperationResult upsertCollection(final String dbName, final String collName, final BsonDocument properties,
        final String requestEtag, final boolean updating, final boolean patching, final boolean checkEtag) {

    if (patching && !updating) {
        return new OperationResult(HttpStatus.SC_NOT_FOUND);
    }

    if (!updating) {
        client.getDatabase(dbName).createCollection(collName);
    }

    ObjectId newEtag = new ObjectId();

    final BsonDocument content = DAOUtils.validContent(properties);

    content.put("_etag", new BsonObjectId(newEtag));
    content.remove("_id"); // make sure we don't change this field

    MongoDatabase mdb = client.getDatabase(dbName);
    MongoCollection<BsonDocument> mcoll = mdb.getCollection("_properties", BsonDocument.class);

    if (checkEtag && updating) {
        BsonDocument oldProperties = mcoll.find(eq("_id", "_properties.".concat(collName)))
                .projection(FIELDS_TO_RETURN).first();

        if (oldProperties != null) {
            BsonValue oldEtag = oldProperties.get("_etag");

            if (oldEtag != null && requestEtag == null) {
                return new OperationResult(HttpStatus.SC_CONFLICT, oldEtag);
            }

            BsonValue _requestEtag;

            if (ObjectId.isValid(requestEtag)) {
                _requestEtag = new BsonObjectId(new ObjectId(requestEtag));
            } else {
                // restheart generates ObjectId etags, but here we support
                // strings as well
                _requestEtag = new BsonString(requestEtag);
            }

            if (Objects.equals(_requestEtag, oldEtag)) {
                return doCollPropsUpdate(collName, patching, updating, mcoll, content, newEtag);
            } else {
                return new OperationResult(HttpStatus.SC_PRECONDITION_FAILED, oldEtag);
            }
        } else {
            // this is the case when the coll does not have properties
            // e.g. it has not been created by restheart
            return doCollPropsUpdate(collName, patching, updating, mcoll, content, newEtag);
        }
    } else {
        return doCollPropsUpdate(collName, patching, updating, mcoll, content, newEtag);
    }
}

From source file:org.restheart.db.CollectionDAO.java

License:Open Source License

/**
 * Deletes a collection./*from   w w  w.  j a  v a2 s. c om*/
 *
 * @param dbName the database name of the collection
 * @param collName the collection name
 * @param requestEtag the entity tag. must match to allow actual write
 * (otherwise http error code is returned)
 * @return the HttpStatus code to set in the http response
 */
OperationResult deleteCollection(final String dbName, final String collName, final String requestEtag,
        final boolean checkEtag) {
    MongoDatabase mdb = client.getDatabase(dbName);
    MongoCollection<Document> mcoll = mdb.getCollection("_properties");

    if (checkEtag) {
        Document properties = mcoll.find(eq("_id", "_properties.".concat(collName)))
                .projection(FIELDS_TO_RETURN).first();

        if (properties != null) {
            Object oldEtag = properties.get("_etag");

            if (oldEtag != null) {
                if (requestEtag == null) {
                    return new OperationResult(HttpStatus.SC_CONFLICT, oldEtag);
                } else if (!Objects.equals(oldEtag.toString(), requestEtag)) {
                    return new OperationResult(HttpStatus.SC_PRECONDITION_FAILED, oldEtag);
                }
            }
        }
    }

    MongoCollection<Document> collToDelete = mdb.getCollection(collName);
    collToDelete.drop();
    mcoll.deleteOne(eq("_id", "_properties.".concat(collName)));
    return new OperationResult(HttpStatus.SC_NO_CONTENT);
}

From source file:org.restheart.db.DatabaseImpl.java

License:Open Source License

/**
 *
 * @param cs the client session//from ww w . j ava  2s.  co  m
 * @param dbName
 * @return the db props
 *
 */
@Override
public BsonDocument getDatabaseProperties(final ClientSession cs, final String dbName) {
    MongoCollection<BsonDocument> propsColl = collectionDAO.getCollection(dbName, META_COLLNAME);

    BsonDocument props = cs == null ? propsColl.find(PROPS_QUERY).limit(1).first()
            : propsColl.find(cs, PROPS_QUERY).limit(1).first();

    if (props != null) {
        props.append("_id", new BsonString(dbName));
    } else if (doesDbExist(cs, dbName)) {
        return new BsonDocument("_id", new BsonString(dbName));
    }

    return props;
}