Example usage for com.mongodb DBCursor close

List of usage examples for com.mongodb DBCursor close

Introduction

In this page you can find the example usage for com.mongodb DBCursor close.

Prototype

@Override
    public void close() 

Source Link

Usage

From source file:com.staticvillage.recommender.indexer.MongoDBIndexer.java

License:Apache License

@Override
public List<Place> getBeans() throws IndexerException {
    DBCollection dbCollection = instanceDB.getCollection(collection);
    DBCursor cursor = dbCollection.find();

    ArrayList<Place> places = new ArrayList<Place>(cursor.count());
    try {//from w  ww . ja v  a2 s.c  om
        while (cursor.hasNext()) {
            places.add(fromDBObject(cursor.next()));
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        cursor.close();
    }

    return places;
}

From source file:com.staticvillage.recommender.indexer.MongoDBIndexer.java

License:Apache License

@Override
public List<Place> getBeans(Object obj) throws IndexerException {
    GeoPoint geoPoint = (GeoPoint) obj;/*from   w w  w  .  j  av a 2  s  .  c o m*/

    BasicDBObject near = new BasicDBObject();
    near.put("geometry", toGeoJSON(geoPoint.getLatitude(), geoPoint.getLongitude()));
    near.put("$maxDistance", 1609);

    BasicDBObject query = new BasicDBObject();
    query.put("$near", near);

    DBCollection dbCollection = instanceDB.getCollection(collection);
    DBCursor cursor = dbCollection.find(query);

    ArrayList<Place> places = new ArrayList<Place>(cursor.count());
    try {
        while (cursor.hasNext()) {
            places.add(fromDBObject(cursor.next()));
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        cursor.close();
    }

    return places;
}

From source file:com.stratio.connector.mongodb.core.engine.query.BasicLogicalWorkflowExecutor.java

License:Apache License

/**
 * Execute an usual query./*from w  w  w . j a  v a 2 s . co m*/
 *
 * @param mongoClient
 *            the MongoDB client.
 * @return the Crossdata ResultSet.
 * @throws MongoValidationException .
 * @throws ExecutionException
 *             if the execution fails or the query specified in the logical workflow is not supported.
 */
public ResultSet executeQuery(MongoClient mongoClient) throws ExecutionException {

    DB db = mongoClient.getDB(logicalWorkflowData.getProject().getCatalogName());
    DBCollection collection = db.getCollection(logicalWorkflowData.getProject().getTableName().getName());
    ResultSet resultSet = new ResultSet();
    resultSet.setColumnMetadata(
            MetaResultUtils.createMetadata(logicalWorkflowData.getProject(), logicalWorkflowData.getSelect()));

    if (logger.isDebugEnabled()) {
        logger.debug("Executing MongoQuery: " + query.get(0) + ", with fields: " + buildProject(false));
    }

    DBCursor cursor = collection.find(query.get(0), buildProject(false));

    if (logicalWorkflowData.getOrderBy() != null) {
        cursor = cursor.sort(buildOrderBy(false));
    }

    if (logicalWorkflowData.getLimit() != null) {
        cursor = cursor.limit(logicalWorkflowData.getLimit().getLimit());
    }

    DBObject rowDBObject;
    try {
        while (cursor.hasNext()) {
            rowDBObject = cursor.next();
            if (logger.isDebugEnabled()) {
                logger.debug("BResult: " + rowDBObject);
            }
            resultSet.add(MetaResultUtils.createRowWithAlias(rowDBObject, logicalWorkflowData.getSelect()));
        }
    } catch (MongoException e) {
        logger.error("Error executing a basic query :" + query.get(0) + ", with fields: " + buildProject(false)
                + "\n Error:" + e.getMessage());
        throw new MongoExecutionException(e.getMessage(), e);
    } finally {
        cursor.close();
    }

    return resultSet;
}

From source file:com.stratio.qa.utils.MongoDBUtils.java

License:Apache License

/**
 * Drop all the data associated to a MongoDB Collection.
 *
 * @param collectionName/* w  ww . j  a va  2  s  .  c  o  m*/
 */
public void dropAllDataMongoDBCollection(String collectionName) {
    DBCollection db = getMongoDBCollection(collectionName);
    DBCursor objectsList = db.find();
    try {
        while (objectsList.hasNext()) {
            db.remove(objectsList.next());
        }
    } finally {
        objectsList.close();
    }
}

From source file:com.stratio.qa.utils.MongoDBUtils.java

License:Apache License

/**
 * Read data from a MongoDB collection.//  w w  w.  jav a  2 s  . c  om
 *
 * @param collection
 * @param table
 * @return {@code List<DBObjects>}
 */
public List<DBObject> readFromMongoDBCollection(String collection, DataTable table) {
    List<DBObject> res = new ArrayList<DBObject>();
    List<String[]> colRel = coltoArrayList(table);
    DBCollection aux = this.dataBase.getCollection(collection);
    for (int i = 1; i < table.raw().size(); i++) {
        // Obtenemos la fila correspondiente
        BasicDBObject doc = new BasicDBObject();
        List<String> row = table.raw().get(i);
        for (int x = 0; x < row.size(); x++) {
            String[] colNameType = colRel.get(x);
            Object data = castSTringTo(colNameType[1], row.get(x));
            doc.put(colNameType[0], data);
        }
        DBCursor cursor = aux.find(doc);
        try {
            while (cursor.hasNext()) {
                res.add(cursor.next());
            }
        } finally {
            cursor.close();
        }
    }
    return res;

}

From source file:com.streamreduce.core.dao.InventoryItemDAO.java

License:Apache License

/**
 * Returns the inventory items for the given connection id.
 *
 * @param connectionId the id of the connection whose inventory items we're interested in
 * @return the list of inventory items or an empty list if there are none
 * @throws IllegalArgumentException if connectionId is null
 *//*from  ww  w  .j a va 2 s .co  m*/
public List<InventoryItem> getInventoryItems(ObjectId connectionId) {
    Preconditions.checkNotNull(connectionId, "connectionId cannot be null.");

    DBCollection collection = getDatastore().getDB().getCollection("inventoryItems");
    BasicDBObject query = new BasicDBObject();
    DBCursor cursor;

    query.put("connection.$id", connectionId);

    cursor = collection.find(query);

    List<InventoryItem> inventoryItems = new ArrayList<>();

    try {
        while (cursor.hasNext()) {
            BasicDBObject rawInventoryItem = (BasicDBObject) cursor.next();

            inventoryItems.add(get((ObjectId) rawInventoryItem.get("_id")));
        }
    } finally {
        cursor.close();
    }

    return inventoryItems;
}

From source file:com.streamreduce.storm.MongoClient.java

License:Apache License

/**
 * Simple helper to create a list of {@link BasicDBObject} from a {@link DBCursor}.
 *
 * @param cursor the cursor to create a list from
 * @return the list of items or an empty list of the query returned zero results
 *//*from ww  w.  j av  a2  s  . c  om*/
private List<BasicDBObject> asList(DBCursor cursor) {
    List<BasicDBObject> list = new ArrayList<>();

    while (cursor.hasNext()) {
        list.add((BasicDBObject) cursor.next());
    }
    cursor.close();
    return list;
}

From source file:com.tengen.FindUsers.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient();
    DB db = client.getDB("blog");
    DBCollection collection = db.getCollection("users");
    //collection.drop();

    // insert 10 documents with a random integer as the value of field "x"

    System.out.println("\nFind all: ");
    DBCursor cursor = collection.find(new BasicDBObject("_id", "andrzej1"));

    try {//from w ww .ja  v a 2  s  .co  m
        while (cursor.hasNext()) {
            DBObject cur = cursor.next();
            System.out.println(cur.get("_id"));
        }
    } finally {
        cursor.close();
    }

    System.out.println("\nCount:");
    long count = collection.count();
    System.out.println(count);
}

From source file:com.tengen.Week3Hw3_1.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient();

    DB database = client.getDB("school");
    DBCollection collection = database.getCollection("students");

    DBCursor cursor = collection.find();
    int student_id = -1;
    int count = 0;

    try {//www  .j a  v  a 2s.  co m
        while (cursor.hasNext()) {
            DBObject student = cursor.next();
            //student.grades;
            BasicDBObject searchQuery = new BasicDBObject().append("_id", student.get("_id"));
            BasicDBList scores = (BasicDBList) student.get("scores");
            BasicDBObject[] scoresArr = scores.toArray(new BasicDBObject[0]);
            double score = 100.0;
            BasicDBObject rem = new BasicDBObject();
            for (BasicDBObject dbObj : scoresArr) {
                String type = dbObj.get("type").toString();
                if (type.equals("homework")) {
                    double s = Double.parseDouble(dbObj.get("score").toString());

                    if (score > s) {
                        score = s;
                        rem = dbObj;
                    }
                }
            }
            BasicDBObject update = new BasicDBObject("scores", rem);
            collection.update(searchQuery, new BasicDBObject("$pull", update));
        }
    } finally {
        cursor.close();
    }
}

From source file:com.university.mongodb.courses.m101j.blogapplication.BlogPostDAO.java

License:Apache License

public List<DBObject> findByDateDescending(int limit) {

    List<DBObject> posts = null;
    // XXX HW 3.2, Work Here
    // Return a list of DBObjects, each one a post from the posts collection
    DBCursor cursor = postsCollection.find(new BasicDBObject()).limit(limit)
            .sort(new BasicDBObject(POST_DATE, -1));
    posts = new ArrayList<>(cursor.count());

    try {//  w  w w  .j a  v a  2  s  .co m
        posts = cursor.toArray();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        cursor.close();
    }

    return posts;
}