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.streamreduce.storm.MongoClient.java

License:Apache License

/**
 * Returns the last two metrics for a given account, metricName and granularity.
 * eg: db.Inbox_4f8c34d3cea02afbc4aa8ce8.find({"metricName":"INVENTORY_ITEM_RESOURCE_USAGE.4f8c3e50cea02afbc4aa8f49.NetworkOut.average","metricGranularity":86400000}).sort({"metricTimestamp":-1}).limit(2);
 *
 * @param metricAccount     the metric account
 * @param metricName        the metric name
 * @param metricGranularity the metric granularity
 * @return the last 2 metrics/*from   w w w . j  ava 2  s. com*/
 */
public List<Map<String, Object>> getLastTwoTuples(String metricAccount, String metricName,
        long metricGranularity) {
    DB metricsDB = getDB("nodeablemsgdb");
    String collectionName = Constants.METRIC_COLLECTION_PREFIX + metricAccount;
    DBCollection metricsCollection = metricsDB.getCollection(collectionName);

    BasicDBObject query = new BasicDBObject();
    query.put("metricName", metricName);
    query.put("metricGranularity", metricGranularity);

    List<Map<String, Object>> list = new ArrayList<>();
    DBCursor cursor = metricsCollection.find(query).sort(new BasicDBObject("metricTimestamp", -1)).limit(2);
    while (cursor.hasNext()) {
        DBObject obj = cursor.next();
        mapMongoToPlainJavaTypes(obj);
        list.add(obj.toMap());
    }
    return list;
}

From source file:com.sube.daos.mongodb.CardMongoDaoImpl.java

License:Apache License

@Override
public List<SubeCard> getCards(SubeCard subeCard) throws InvalidSubeCardException {
    DBCollection collection = getCardCollection();
    DBCursor cursor = collection.find(getCardQuery(subeCard));
    Iterator<DBObject> iterator = cursor.iterator();
    List<SubeCard> cards = new ArrayList<SubeCard>();
    while (iterator.hasNext()) {
        DBObject dbObject = iterator.next();
        cards.add(subeCardParser.parse(dbObject));
    }//from  ww w .ja  v  a  2s . c o  m
    return cards;
}

From source file:com.sube.daos.mongodb.CardUsagesMongoDaoImpl.java

License:Apache License

@Override
public List<SubeCardUsage> listLastUsage(SubeCard subeCard, int limit) throws InvalidSubeCardException {
    DBCollection cardUsagesCollection = getCardUsagesCollection();
    BasicDBObject query = new BasicDBObject();
    query.put("subeCard", subeCardRefGenerator.generateDBRef(subeCard));
    DBCursor dbCursor = cardUsagesCollection.find(query);
    int i = 0;//from   w  ww.ja v a2s.  co  m
    List<SubeCardUsage> subeCardUsages = new ArrayList<SubeCardUsage>();
    while (dbCursor.hasNext() && i < limit) {
        DBObject next = dbCursor.next();
        subeCardUsages.add(subeCardUsageParser.parse(next));
        i++;
    }
    return subeCardUsages;
}

From source file:com.sube.daos.mongodb.GenericProviderDaoImpl.java

License:Apache License

@Override
public List<Provider> getProviderByName(String name, int limit) {
    List<Provider> providers = new ArrayList<Provider>();
    DBCollection collection = getProvidersCollection();
    BasicDBObject query = new BasicDBObject();
    BasicDBObject legalPerson = new BasicDBObject();
    legalPerson.put("fantasyName", name);
    legalPerson.put("legalName", name);
    query.put("providerName", name);
    DBCursor cursor = collection.find(query);
    int i = 0;//from  www .  j  a v a2  s  . co  m
    while (cursor.hasNext() && i < limit) {
        providers.add(providerParser.parse(cursor.next()));
        i++;
    }
    return providers;
}

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  w w.  j av  a2  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.tilab.fiware.metaware.dao.impls.mongodb.AlgorithmDao.java

License:Open Source License

/**
 * Checks if the selected Ids in permissions (can be user, department, or company) exist in
 * users, departments, or companies collection; if so, returns the list of permissions.
 *
 * @param algorithm             the selected algorithm.
 * @param usersCollection       the collection of registered users.
 * @param departmentsCollection the collection of registered departments.
 * @param companiesCollection   the collection of registered companies.
 * @return permissionsList the list of permissions.
 */// w w  w.j  a  v  a2  s  .co  m
private List<Permission> checkPermissions(Algorithm algorithm, DBCollection usersCollection,
        DBCollection departmentsCollection, DBCollection companiesCollection) {

    // Check if the field exists
    if (algorithm.getPermissions() == null) {
        log.error(MSG_ERR_NOT_VALID_PERMISSION);
        return null;
    }

    // Prepare lists
    List rawPermissionsList = new ArrayList(algorithm.getPermissions()); // unspecified type generates maven warning
    List<Permission> permissionsList = new ArrayList<>();

    log.debug("Inserted permissions (raw): " + rawPermissionsList.toString());

    // Convert from raw to Permission objects
    for (Object rawCurrPerm : rawPermissionsList) {
        Permission currPerm = new Permission((Map) rawCurrPerm);
        if (!ObjectId.isValid(currPerm.getReference())) {
            log.error(MSG_ERR_NOT_VALID_PERMISSION);
            return null;
        }
        // TODO: insert check for "perm" string too
        currPerm.setReferenceId(new ObjectId(currPerm.getReference())); // transform the id from string to ObjectId
        permissionsList.add(currPerm);
    }

    log.debug("Inserted permissions: " + permissionsList.toString());

    // Make the query
    BasicDBObject query = new BasicDBObject();
    for (Permission currPerm : permissionsList) {
        query.put("_id", currPerm.getReferenceId()); // query by id
        int resNumUser = usersCollection.find(query).count(); // count users
        int resNumDepartment = departmentsCollection.find(query).count(); // count departments
        int resNumCompany = companiesCollection.find(query).count(); // count companies
        if ((resNumUser + resNumDepartment + resNumCompany) == 0) {
            log.error(MSG_ERR_NOT_VALID_PERMISSION);
            return null;
        }
    }

    return permissionsList;
}

From source file:com.tilab.fiware.metaware.dao.impls.mongodb.DatasetDao.java

License:Open Source License

/**
 * Checks if the selected users (can be user, department, or company) exist in users,
 * departments, or companies collection; if so, return the list of ObjectIds.
 *
 * @param dataset               the selected dataset
 * @param usersCollection       the collection of registered users.
 * @param departmentsCollection the collection of registered departments.
 * @param companiesCollection   the collection of registered companies.
 * @return idList the list of Ids./*from ww  w . j  av a2  s .c  o m*/
 */
private List<Permission> checkPermissions(Dataset dataset, DBCollection usersCollection,
        DBCollection departmentsCollection, DBCollection companiesCollection) {

    // Check if the field exists
    if (dataset.getPermissions() == null) {
        return null;
    }

    // Prepare lists
    List rawPermissionsList = new ArrayList(dataset.getPermissions());
    List<Permission> permissionsList = new ArrayList();

    log.debug("Inserted permissions (raw): " + rawPermissionsList.toString());

    // Convert from raw to Permission objects
    for (Object rawCurrPerm : rawPermissionsList) {
        Permission currPerm = new Permission((Map) rawCurrPerm);
        if (!ObjectId.isValid(currPerm.getReference())) {
            return null;
        }
        // TODO: insert check for "perm" string too
        currPerm.setReferenceId(new ObjectId(currPerm.getReference()));
        permissionsList.add(currPerm);
    }

    log.debug("Inserted permissions: " + permissionsList.toString());

    // Make the query
    BasicDBObject query = new BasicDBObject();

    for (Permission currPerm : permissionsList) {
        query.put("_id", currPerm.getReferenceId()); // query by id
        int resNumUser = usersCollection.find(query).count(); // count users
        int resNumDepartment = departmentsCollection.find(query).count(); // count departments
        int resNumCompany = companiesCollection.find(query).count(); // count companies
        if ((resNumUser + resNumDepartment + resNumCompany) == 0) {
            return null;
        }
    }

    return permissionsList;
}

From source file:com.tilab.fiware.metaware.dao.impls.mongodb.DataSourceDao.java

License:Open Source License

/**
 * Checks if the selected Ids in permissions (can be user, department, or company) exist in
 * users, departments, or companies collections; if so, returns the list of permissions.
 *
 * @param datasource            the selected data source.
 * @param usersCollection       the collection of registered users.
 * @param departmentsCollection the collection of registered departments.
 * @param companiesCollection   the collection of registered companies.
 * @return permissionsList the list of permissions.
 *//*from ww  w  .j a  va  2  s  .  co m*/
private List<Permission> checkPermissions(DataSource datasource, DBCollection usersCollection,
        DBCollection departmentsCollection, DBCollection companiesCollection) {
    // Check if the field exists
    if (datasource.getPermissions() == null) {
        return null; // no permissions provided
    }

    // Prepare lists
    List rawPermissionsList = new ArrayList(datasource.getPermissions()); // unspecified type generates maven warning
    List<Permission> permissionsList = new ArrayList<>();

    log.debug("Inserted permissions (raw): " + rawPermissionsList.toString());

    // Convert from raw to Permission objects
    for (Object rawCurrPerm : rawPermissionsList) {
        Permission currPerm = new Permission((Map) rawCurrPerm);
        if (!ObjectId.isValid(currPerm.getReference())) {
            return null; // the associated id isn't valid
        }
        // TODO: insert check for "perm" string too
        currPerm.setReferenceId(new ObjectId(currPerm.getReference())); // transform the id from string to objectid
        permissionsList.add(currPerm);
    }

    log.debug("Inserted permissions: " + permissionsList.toString());

    // Make the query
    BasicDBObject query = new BasicDBObject();
    for (Permission currPerm : permissionsList) {
        query.put("_id", currPerm.getReferenceId()); // query by id
        int resNumUser = usersCollection.find(query).count(); // count users
        int resNumDepartment = departmentsCollection.find(query).count(); // count departments
        int resNumCompany = companiesCollection.find(query).count(); // count companies
        if ((resNumUser + resNumDepartment + resNumCompany) == 0) {
            return null; // found nothing
        }
    }

    return permissionsList;
}

From source file:com.tilab.fiware.metaware.dao.impls.mongodb.ProcessDao.java

License:Open Source License

/**
 * Checks if the selected Ids in permissions (can be user, department, or company) exist in
 * users, departments, or companies collection; if so, returns the list of permissions.
 *
 * @param process               the selected process.
 * @param usersCollection       the collection of registered users.
 * @param departmentsCollection the collection of registered departments.
 * @param companiesCollection   the collection of registered companies.
 * @return permissionsList the list of permissions.
 *///  ww  w.  ja v a  2s .  c o  m
private List<Permission> checkPermissions(Process process, DBCollection usersCollection,
        DBCollection departmentsCollection, DBCollection companiesCollection) {
    // Check if the field exists
    if (process.getPermissions() == null) {
        log.error(MSG_ERR_NOT_VALID_PERMISSION);
        return null;
    }

    // Prepare lists
    List rawPermissionsList = new ArrayList(process.getPermissions()); // uspecified type generates maven warning
    List<Permission> permissionsList = new ArrayList<>();

    log.debug("Inserted permissions (raw): " + rawPermissionsList.toString());

    // Convert from raw to Permission objects
    for (Object rawCurrPerm : rawPermissionsList) {
        Permission currPerm = new Permission((Map) rawCurrPerm);
        if (!ObjectId.isValid(currPerm.getReference())) {
            log.error(MSG_ERR_NOT_VALID_PERMISSION);
            return null;
        }
        // TODO: insert check for "perm" string too
        currPerm.setReferenceId(new ObjectId(currPerm.getReference())); // transform the Id from string to ObjectId

        permissionsList.add(currPerm);
    }

    log.debug("Inserted permissions: " + permissionsList.toString());

    // Make the query
    BasicDBObject query = new BasicDBObject();
    for (Permission currPerm : permissionsList) {
        query.put("_id", currPerm.getReferenceId()); // query by id
        int resNumUser = usersCollection.find(query).count(); // count users
        int resNumDepartment = departmentsCollection.find(query).count(); // count departments
        int resNumCompany = companiesCollection.find(query).count(); // count companies
        if ((resNumUser + resNumDepartment + resNumCompany) == 0) {
            log.error(MSG_ERR_NOT_VALID_PERMISSION);
            return null;
        }
    }

    return permissionsList;
}

From source file:com.tml.pathummoto.Dao.BillDao.java

public ArrayList<Bill> searchBill(String no) {

    MongoClient mongoClient = new MongoClient("localhost", 27017);

    // Now connect to your databases
    DB db = mongoClient.getDB("pathumdb");
    System.out.println("Connect to database successfully");

    DBCollection coll = db.getCollection("Bill");
    System.out.println("Collection user selected successfully");

    BasicDBObject whereQuery = new BasicDBObject();
    whereQuery.put("vehicleNo", no);
    DBCursor cursor = coll.find(whereQuery);

    ArrayList<Bill> bills = new ArrayList<Bill>();

    while (cursor.hasNext()) {
        BasicDBObject doc = (BasicDBObject) cursor.next();

        if (doc != null) {
            Bill bill = new Bill();
            bill.setDate(doc.getDate("Date"));
            bill.setKm(doc.getInt("km"));
            bill.setPayment(doc.getInt("payment"));
            bill.setService(doc.getInt("service"));
            bill.setTotalCost(doc.getInt("total"));
            String array = "";
            int partSize = doc.getInt("partsSize");
            for (int i = 0; i < partSize; i++) {
                String parts = "part" + i;
                String quentity = "quant" + i;
                array = array + doc.getString(parts) + " : " + doc.getInt(quentity) + "\n";

            }//from   w  ww  .j  a v  a 2  s . co  m
            bill.setParts(array);
            bills.add(bill);
        }
    }
    return bills;
}