Example usage for com.mongodb DBCollection find

List of usage examples for com.mongodb DBCollection find

Introduction

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

Prototype

public DBCursor find(final DBObject query) 

Source Link

Document

Select documents in collection and get a cursor to the selected documents.

Usage

From source file:com.socialsky.mods.MongoPersistor.java

License:Apache License

private void doFind(Message<JsonObject> message) {
    String collection = getMandatoryString("collection", message);
    if (collection == null) {
        return;//from   w w  w . j  ava  2s  .  c o m
    }
    Integer limit = (Integer) message.body().getNumber("limit");
    if (limit == null) {
        limit = -1;
    }
    Integer skip = (Integer) message.body().getNumber("skip");
    if (skip == null) {
        skip = -1;
    }
    Integer batchSize = (Integer) message.body().getNumber("batch_size");
    if (batchSize == null) {
        batchSize = 100;
    }
    Integer timeout = (Integer) message.body().getNumber("timeout");
    if (timeout == null || timeout < 0) {
        timeout = 10000; // 10 seconds
    }
    JsonObject matcher = message.body().getObject("matcher");
    JsonObject keys = message.body().getObject("keys");

    Object hint = message.body().getField("hint");
    Object sort = message.body().getField("sort");
    DBCollection coll = db.getCollection(collection);
    DBCursor cursor;
    if (matcher != null) {
        cursor = (keys == null) ? coll.find(jsonToDBObject(matcher))
                : coll.find(jsonToDBObject(matcher), jsonToDBObject(keys));
    } else {
        cursor = coll.find();
    }
    if (skip != -1) {
        cursor.skip(skip);
    }
    if (limit != -1) {
        cursor.limit(limit);
    }
    if (sort != null) {
        cursor.sort(sortObjectToDBObject(sort));
    }
    if (hint != null) {
        if (hint instanceof JsonObject) {
            cursor.hint(jsonToDBObject((JsonObject) hint));
        } else if (hint instanceof String) {
            cursor.hint((String) hint);
        } else {
            throw new IllegalArgumentException("Cannot handle type " + hint.getClass().getSimpleName());
        }
    }
    sendBatch(message, cursor, batchSize, timeout);
}

From source file:com.softinstigate.restheart.db.CollectionDAO.java

License:Open Source License

/**
 * Returs the documents of the collection applying, sorting, pagination and
 * filtering./*from w  w w.java 2s .  com*/
 *
 * @param coll the mongodb DBCollection object
 * @param page the page number
 * @param pagesize the size of the page
 * @param sortBy the Deque collection of fields to use for sorting (prepend
 * field name with - for descending sorting)
 * @param filters the filters to apply. it is a Deque collection of mongodb
 * query conditions.
 * @return
 * @throws JSONParseException
 */
public static ArrayList<DBObject> getCollectionData(DBCollection coll, int page, int pagesize,
        Deque<String> sortBy, Deque<String> filters) throws JSONParseException {
    // apply sort_by
    DBObject sort = new BasicDBObject();

    if (sortBy == null || sortBy.isEmpty()) {
        sort.put("_id", 1);
    } else {
        sortBy.stream().forEach((sf) -> {
            sf = sf.replaceAll("_lastupdated_on", "_etag"); // _lastupdated is not stored and actually generated from @tag

            if (sf.startsWith("-")) {
                sort.put(sf.substring(1), -1);
            } else if (sf.startsWith("+")) {
                sort.put(sf.substring(1), -1);
            } else {
                sort.put(sf, 1);
            }
        });
    }

    // apply filter
    final BasicDBObject query = new BasicDBObject(DOCUMENTS_QUERY);

    if (filters != null) {
        filters.stream().forEach((String f) -> {
            BSONObject filterQuery = (BSONObject) JSON.parse(f);
            query.putAll(filterQuery); // this can throw JSONParseException for invalid filter parameters
        });
    }

    ArrayList<DBObject> data = getDataFromCursor(
            coll.find(query).sort(sort).limit(pagesize).skip(pagesize * (page - 1)));

    data.forEach(row -> {
        Object etag = row.get("_etag");

        if (etag != null && ObjectId.isValid("" + etag)) {
            ObjectId _etag = new ObjectId("" + etag);

            row.put("_lastupdated_on", Instant.ofEpochSecond(_etag.getTimestamp()).toString());
        }
    });

    return data;
}

From source file:com.softlyinspired.jlw.connections.dbConnection.java

License:Open Source License

public boolean checkExisting() {
    /**//from   w  w  w.ja  va  2  s  .  c  om
     * sets value of concernExists;
     */
    boolean nameExists;
    try {
        /* Get the database collection */
        DBCollection connectionColl = repoConnection.getConnectionCollection();
        if (connectionColl == null) {
            return false;
        }
        ;
        // search for the id
        BasicDBObject query = new BasicDBObject();
        query.put("name", connectionName);

        DBCursor checkDoc = connectionColl.find(query).limit(1);

        if (checkDoc.count() == 0) {
            nameExists = false;
        } else {
            nameExists = true;
            currentConnectionDoc = checkDoc.next();
        }

    } catch (Exception e) {
        System.out.println("Connection does not exist");
        nameExists = false;
    }
    return nameExists;
}

From source file:com.softlyinspired.jlw.reports.ReportReference.java

License:Open Source License

/**
 * // www.  j a  v a  2 s.  c o  m
 * @return boolean - true if report id exists
 */
public boolean checkExisting() {
    /**
     * Returns if report reference exists or not;
     */
    boolean IdExists;
    try {
        /* Get the database collection */
        DBCollection coll = repoConnection.getReportsCollection();
        if (coll == null) {
            return false;
        }
        ;

        BasicDBObject query = new BasicDBObject();
        query.put("reportId", reportId);

        DBCursor checkDoc = coll.find(query).limit(1);
        if (checkDoc.count() == 0) {
            IdExists = false;
        } else {
            IdExists = true;
            currentReportDoc = checkDoc.next();
            reportName = currentReportDoc.get("name").toString();
            reportType = currentReportDoc.get("type").toString();
            reportDescription = currentReportDoc.get("description").toString();
            reportCategory = currentReportDoc.get("category").toString();
            reportLocation = currentReportDoc.get("reportLocation").toString();
        }

    } catch (Exception e) {
        System.out.println("Report does not exist");
        IdExists = false;
    }
    return IdExists;
}

From source file:com.sql2nosql.SQLExecuter.java

License:Open Source License

public static String execute(String SQL) throws Exception {

    Settings settings = SettingsImporter.importSettings("sql2nosql.settings.xml");

    MongoClient mongo = new MongoClient(settings.getHost(), settings.getPort().intValue());

    DB db = mongo.getDB(settings.getDbname());

    HashMap<String, LinkedHashMap<String, Object>> list = new HashMap<String, LinkedHashMap<String, Object>>();
    SQLParser parser = new SQLParser();
    StatementNode node = parser.parseStatement(SQL);

    QueryTreeVisitor fdg = new QueryTreeVisitor(list);
    node.accept(fdg);//from  ww w. j  av a 2  s .  co m

    String string = null;
    LinkedHashMap<String, Object> tableList = list.get(TABLE);
    for (Map.Entry<String, Object> entry : tableList.entrySet()) {
        string = entry.getKey();
        Object object = entry.getValue();

    }
    DBCollection table = db.getCollection(string.toLowerCase());

    LinkedHashMap<String, Object> whereList = list.get(WHERE);
    String string1 = null;
    Object object = null;
    for (Map.Entry<String, Object> entry : whereList.entrySet()) {
        string1 = entry.getKey();
        object = entry.getValue();

    }

    BasicDBObject searchQuery = new BasicDBObject();

    searchQuery.put(string1.toLowerCase(), object.toString());

    DBCursor cursor = table.find(searchQuery);

    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }

    return null;
}

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  a  va 2  s  . co  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.qa.specs.WhenGSpec.java

License:Apache License

/**
 * Execute a query on (mongo) database//w w w  .j a v a2 s.c o m
 *
 * @param query         path to query
 * @param type          type of data in query (string or json)
 * @param collection    collection in database
 * @param modifications modifications to perform in query
 */
@When("^I execute a query '(.+?)' of type '(json|string)' in mongo '(.+?)' database using collection '(.+?)' with:$")
public void sendQueryOfType(String query, String type, String database, String collection,
        DataTable modifications) throws Exception {
    try {
        commonspec.setResultsType("mongo");
        String retrievedData = commonspec.retrieveData(query, type);
        String modifiedData = commonspec.modifyData(retrievedData, type, modifications);
        commonspec.getMongoDBClient().connectToMongoDBDataBase(database);
        DBCollection dbCollection = commonspec.getMongoDBClient().getMongoDBCollection(collection);
        DBObject dbObject = (DBObject) JSON.parse(modifiedData);
        DBCursor cursor = dbCollection.find(dbObject);
        commonspec.setMongoResults(cursor);
    } catch (Exception e) {
        commonspec.getExceptions().add(e);
    }
}

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

License:Apache License

/**
 * Read data from a MongoDB collection./*from  ww w.j  a  v  a 2s  .  c o  m*/
 *
 * @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 v a  2s  . 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.core.dao.MetricDAO.java

License:Apache License

/**
 * Returns a list of metrics.//  ww  w  . ja v  a2  s  . c  o  m
 *
 * @param accountId the account the metrics should be queried from
 * @param metricName the metric name
 * @param criteria the metric criteria
 * @param granularity the metric granularity
 * @param startTime the time of the earliest entry to return (Should be null if it doesn't matter)
 * @param endTime the time of the latest entry to return (Should be null if it doesn't matter)
 * @param pageNum the "page" number
 * @param pageSize the number of items metrics page
 *
 * @return list of metrics
 */
public List<DBObject> getMetrics(String accountId, String metricName, Map<String, List<String>> criteria,
        Long granularity, Long startTime, Long endTime, int pageNum, int pageSize) {
    DB db = messageDatastore.getDB();
    DBCollection collection = db.getCollection("Metric_" + accountId);
    BasicDBObject query = new BasicDBObject();

    query.put("metricName", metricName);
    query.put("granularity", granularity);

    for (Map.Entry<String, List<String>> criteriaEntry : criteria.entrySet()) {
        String criteriaName = criteriaEntry.getKey();
        List<String> criteriaValue = criteriaEntry.getValue();
        String queryKey = "metricCriteria." + criteriaName;

        if (criteriaValue.size() == 1) {
            String value = criteriaValue.get(0);

            if (value.equals("*")) {
                // Criteria is a wildcard so return metrics that have the metric criteria
                query.put(queryKey, new BasicDBObject("$exists", true));
            } else {
                // Criteria is an explicit value
                query.put(queryKey, value);
            }
        } else {
            // Criteria is an array/list of values
            query.put(queryKey, new BasicDBObject("$in", criteriaValue));
        }
    }

    if (startTime != null || endTime != null) {
        BasicDBObject timestampQuery = new BasicDBObject();

        if (startTime != null) {
            timestampQuery.put("$gte", startTime);
        }

        if (endTime != null) {
            timestampQuery.put("$lte", endTime);
        }

        query.put("metricTimestamp", timestampQuery);
    }

    return collection.find(query).sort(new BasicDBObject("metricTimestamp", -1)).skip((pageNum - 1) * pageSize)
            .limit(pageSize).toArray();
}