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.facebook.presto.mongodb.MongoSession.java

License:Apache License

public MongoCursor<Document> execute(MongoSplit split, List<MongoColumnHandle> columns) {
    Document output = new Document();
    for (MongoColumnHandle column : columns) {
        output.append(column.getName(), 1);
    }/*from   w  w  w .  j  a v a  2s .  co m*/
    MongoCollection<Document> collection = getCollection(split.getSchemaTableName());
    FindIterable<Document> iterable = collection.find(buildQuery(split.getTupleDomain())).projection(output);

    if (cursorBatchSize != 0) {
        iterable.batchSize(cursorBatchSize);
    }

    return iterable.iterator();
}

From source file:com.facebook.presto.mongodb.MongoSession.java

License:Apache License

private Document getTableMetadata(SchemaTableName schemaTableName) throws TableNotFoundException {
    String schemaName = schemaTableName.getSchemaName();
    String tableName = schemaTableName.getTableName();

    MongoDatabase db = client.getDatabase(schemaName);
    MongoCollection<Document> schema = db.getCollection(schemaCollection);

    Document doc = schema.find(new Document(TABLE_NAME_KEY, tableName)).first();

    if (doc == null) {
        if (!collectionExists(db, tableName)) {
            throw new TableNotFoundException(schemaTableName);
        } else {/*from  ww w .jav  a 2s  .  co m*/
            Document metadata = new Document(TABLE_NAME_KEY, tableName);
            metadata.append(FIELDS_KEY, guessTableFields(schemaTableName));

            schema.createIndex(new Document(TABLE_NAME_KEY, 1), new IndexOptions().unique(true));
            schema.insertOne(metadata);

            return metadata;
        }
    }

    return doc;
}

From source file:com.futuremove.cacheServer.service.impl.CarDynPropsServiceImpl.java

public FindIterable<Document> getNearByNeededCar(Long maxDistance, CarDynProps centerFilter) {
    if (maxDistance < 200L)
        maxDistance = 200L;/*from  w  ww. j av  a2 s.com*/
    MongoCollection<Document> collection = this.getCollection();
    Document filterDoc = centerFilter.toDocument();
    Document locFilter = new Document();
    locFilter.put("$near", new Document().append("$geometry", centerFilter.location.toDocument())
            .append("$maxDistance", maxDistance));
    filterDoc.put("location", locFilter);
    if (centerFilter.dataUpdateTime != null) {
        //?
        filterDoc.put("dataUpdateTime", new Document().append("$gt", centerFilter.dataUpdateTime));
    }
    return collection.find(filterDoc);
}

From source file:com.github.cherimojava.data.mongo.entity.EntityInvocationHandler.java

License:Apache License

/**
 * searches for the given Id within the MongoCollection and returns, if the id was found the corresponding entity.
 * If the entity wasn't found null will be returned
 *
 * @param collection//from ww w.  j av a2  s . c  o  m
 *            where the entity class is stored in
 * @param id
 *            of the entity to load
 * @param <T>
 *            Type of the entity
 * @return returns the entity belonging to the given Id within the collection or null if no such entity exists in
 *         the given collection
 */
@SuppressWarnings("unchecked")
static <T extends Entity> T find(MongoCollection<T> collection, Object id) {
    try (MongoCursor<? extends Entity> curs = collection.find(new Document(Entity.ID, id)).limit(1)
            .iterator()) {
        return (T) ((curs.hasNext()) ? curs.next() : null);
    }
}

From source file:com.github.terma.fastselect.benchmark.PlayerMongoDb.java

License:Apache License

@Override
public Object selectLimit() throws Exception {
    MongoCollection collection = database.getCollection("myCollection");
    MongoCursor<Document> cursor = collection.find(Document.parse("{\"prg\": {$in: ["
            + DemoData.SCALAR_IN_1_AS_STRING + "]}, \"prr\": {$in: [" + DemoData.SCALAR_IN_2_AS_STRING + "]}}"))
            .limit(25).iterator();//from   w  w w  . ja  v a 2  s  .  c  om

    List<Object> r = new ArrayList<>();
    while (cursor.hasNext()) {
        r.add(cursor.next());
    }

    cursor.close();
    return r.size();
}

From source file:com.github.terma.fastselect.benchmark.PlayerMongoDb.java

License:Apache License

@Override
public Object selectOrderByLimit() throws Exception {
    MongoCollection collection = database.getCollection("myCollection");
    MongoCursor<Document> cursor = collection
            .find(Document.parse("{\"prg\": {$in: [" + DemoData.SCALAR_IN_1_AS_STRING + "]}, \"prr\": {$in: ["
                    + DemoData.SCALAR_IN_2_AS_STRING + "]}}"))
            .sort(Document.parse("{prr: 1}")).limit(25).iterator();

    List<Object> r = new ArrayList<>();
    while (cursor.hasNext()) {
        r.add(cursor.next());//from   w  ww.j  ava 2s.co m
    }

    cursor.close();
    return r.size();
}

From source file:com.gs.obevo.mongodb.impl.MongoDbChangeAuditDao.java

License:Apache License

@Override
public void updateOrInsertChange(Change change, DeployExecution deployExecution) {
    MongoCollection<Document> auditCollection = getAuditCollection(change);
    MutableList<Document> docs = iterableToCollection(auditCollection.find(getChangeFilter(change)));

    if (docs.size() > 1) {
        throw new IllegalStateException("Not expecting multiple changes for this key [" + change.getObjectName()
                + "." + change.getChangeName() + "], but found " + docs);
    } else if (docs.isEmpty()) {
        insertNewChange(change, deployExecution);
    } else {/*w w w  . j a  v a2s  .c o  m*/
        Document previousDoc = docs.get(0);
        Date timeInserted = previousDoc.getDate(timeInsertedColumn);
        auditCollection.replaceOne(getChangeFilter(change),
                createDocFromChange(change, deployExecution, timeInserted));
    }
}

From source file:com.ibm.research.mongotx.lrc.LatestReadCommittedTxDB.java

License:Open Source License

private boolean isSharding() {
    try {//from w w  w .  ja v  a2 s .com
        MongoDatabase configDB = client.getDatabase("config");
        if (configDB == null)
            return false;

        MongoCollection<Document> databasesCol = configDB.getCollection("databases");
        if (databasesCol == null)
            return false;

        Iterator<Document> dbInfoItr = databasesCol.find(new Document(ATTR_ID, db.getName())).iterator();

        if (!dbInfoItr.hasNext())
            return false;

        return (Boolean) dbInfoItr.next().get("partitioned");
    } catch (MongoQueryException ex) {
        return false;
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }
}

From source file:com.ibm.research.mongotx.lrc.LRCTxDBCollection.java

License:Open Source License

private void initShardKeysIfNecessary() {
    if (!txDB.isSharding)
        return;//from  w  ww  . ja v a 2 s.  c  o  m

    try {
        MongoDatabase configDB = txDB.client.getDatabase("config");
        if (configDB == null)
            return;

        MongoCollection<Document> collectionsCol = configDB.getCollection("collections");
        if (collectionsCol == null)
            return;

        Iterator<Document> itrShardInfo = collectionsCol.find(
                new Document(ATTR_ID, txDB.db.getName() + "." + baseCol.getNamespace().getCollectionName()))
                .iterator();
        if (!itrShardInfo.hasNext())
            return;

        Document shardKeys = (Document) itrShardInfo.next().get("key");
        if (shardKeys == null)
            return;

        this.shardKeys.addAll(shardKeys.keySet());

    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, "shardkey init error. msg=" + ex.getMessage(), ex);
    }
}

From source file:com.imaginea.mongodb.services.impl.DocumentServiceImpl.java

License:Apache License

/**
 * Updates a document inside a collection in a database in mongo to which user is connected to.
 *
 * @param dbName Name of Database//from  www .  j a  v a2 s .c  o  m
 * @param collectionName Name of Collection from which to get all Documents
 * @param _id Id of Document to be updated
 * @param newData new Document value.
 * @return Update status
 * @throws DatabaseException throw super type of UndefinedDatabaseException
 * @throws ValidationException throw super type of
 *         EmptyDatabaseNameException,EmptyCollectionNameException ,EmptyDocumentDataException
 * @throws CollectionException throw super type of UndefinedCollectionException
 * @throws DocumentException throw super type of UpdateDocumentException
 */

public String updateDocument(String dbName, String collectionName, String _id, Document newData)
        throws DatabaseException, CollectionException, DocumentException, ValidationException {

    if (dbName == null) {
        throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database name is null");

    }
    if (dbName.equals("")) {
        throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database Name Empty");
    }

    if (collectionName == null) {
        throw new CollectionException(ErrorCodes.COLLECTION_NAME_EMPTY, "Collection name is null");
    }
    if (collectionName.equals("")) {
        throw new CollectionException(ErrorCodes.COLLECTION_NAME_EMPTY, "Collection Name Empty");
    }
    String result = null;

    try {
        // if (!databaseService.getDbList().contains(dbName)) {
        //   throw new DatabaseException(ErrorCodes.DB_DOES_NOT_EXISTS,
        //       "DB [" + dbName + "] DOES NOT EXIST");
        // }

        if (!collectionService.getCollList(dbName).contains(collectionName)) {
            throw new CollectionException(ErrorCodes.COLLECTION_DOES_NOT_EXIST,
                    "COLLECTION [ " + collectionName + "] _DOES_NOT_EXIST in Db [ " + dbName + "]");
        }
        if (_id == null) {
            throw new DocumentException(ErrorCodes.DOCUMENT_EMPTY, "Document is empty");
        }

        String newId = (String) newData.get("_id");

        if (newId == null) {
            throw new DocumentException(ErrorCodes.INVALID_OBJECT_ID, "Object Id is invalid.");
        }
        if (newId.equals("")) {
            throw new DocumentException(ErrorCodes.INVALID_OBJECT_ID, "Object Id is invalid.");
        }

        ObjectId docId = new ObjectId(_id);

        if (!newId.equals(_id)) {
            throw new DocumentException(ErrorCodes.UPDATE_OBJECT_ID_EXCEPTION, "_id cannot be updated.");
        }

        MongoCollection<Document> collection = mongoInstance.getDatabase(dbName).getCollection(collectionName);

        Document document = collection.find(Filters.eq("_id", docId)).first();

        if (document != null) {

            ObjectId objectId = document.getObjectId("_id");

            newData.put("_id", objectId);

            Document updateData = new Document("$set", newData);
            collection.updateOne(Filters.eq("_id", objectId), updateData);

        } else {
            throw new DocumentException(ErrorCodes.DOCUMENT_DOES_NOT_EXIST, "Document does not exist !");
        }

    } catch (IllegalArgumentException e) {
        // When error converting object Id

        throw new DocumentException(ErrorCodes.INVALID_OBJECT_ID, "Object Id is invalid.");

    } catch (MongoException e) {
        throw new DocumentException(ErrorCodes.DOCUMENT_UPDATE_EXCEPTION, e.getMessage());
    }
    result = "Document: [" + newData + "] has been updated.";

    return result;
}