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.mycompany.bean.PlytaService.java

public List<Plyta> searchByTytul(String DBName, String CollectionName, String paramTytul) throws Exception {
    List<Plyta> plyty = new ArrayList();
    try {/*ww  w  .  ja  v  a  2 s  .c om*/
        DBCollection collection = getConnection(DBName, CollectionName);
        BasicDBObject TytulIndex = new BasicDBObject();
        TytulIndex.put("tytul", 1);
        collection.createIndex(TytulIndex, "TytulIndex", true); // tworzy index jeeli takiego nie ma
        BasicDBObject query = new BasicDBObject();
        query.append("tytul", paramTytul);
        DBCursor cur = collection.find(query);
        DBObject o;
        Plyta p;
        while (cur.hasNext()) {
            p = new Plyta();
            o = cur.next();
            p.setTytul((String) o.get("tytul"));
            p.setAutor((List<String>) o.get("autor"));
            p.setLiczbaUtworow((Integer) o.get("liczbaUtworow"));
            p.setWytwornia((List<String>) o.get("wytwornia"));
            p.setRokWydania((Integer) o.get("rokWydania"));
            p.setProducent((String) o.get("producent"));
            p.setGatunek((List<String>) o.get("gatunek"));
            p.setDlugosc((String) o.get("dlugosc"));
            p.setSingle((List<String>) o.get("single"));
            p.setNagrody((List<String>) o.get("nagrody"));
            p.setRodzajAlbumu((String) o.get("rodzajAlbumu"));
            p.setUtwory((List<Utwor>) o.get("utwory"));
            plyty.add(p);
        }
        log.log(Level.INFO, "Zapytanie wykonane poprawnie");
    } catch (Exception e) {
        log.log(Level.SEVERE, "Blad wykonania zapytania");
    }
    return plyty;
}

From source file:com.mycompany.bean.PlytaService.java

public List<Plyta> searchByAutor(String DBName, String CollectionName, String paramAutor) throws Exception {
    List<Plyta> plyty = new ArrayList();
    try {/*from  w  w w.jav a  2s.com*/
        DBCollection collection = getConnection(DBName, CollectionName);
        BasicDBObject AutorIndex = new BasicDBObject();
        AutorIndex.put("autor", 1);
        collection.createIndex(AutorIndex, "IndexAutor");
        BasicDBObject query = new BasicDBObject();
        query.append("autor", paramAutor);
        DBCursor cur = collection.find(query);
        DBObject o;
        Plyta p;
        while (cur.hasNext()) {
            p = new Plyta();
            o = cur.next();
            p.setTytul((String) o.get("tytul"));
            p.setAutor((List<String>) o.get("autor"));
            p.setLiczbaUtworow((Integer) o.get("liczbaUtworow"));
            p.setWytwornia((List<String>) o.get("wytwornia"));
            p.setRokWydania((Integer) o.get("rokWydania"));
            p.setProducent((String) o.get("producent"));
            p.setGatunek((List<String>) o.get("gatunek"));
            p.setDlugosc((String) o.get("dlugosc"));
            p.setSingle((List<String>) o.get("single"));
            p.setNagrody((List<String>) o.get("nagrody"));
            p.setRodzajAlbumu((String) o.get("rodzajAlbumu"));
            p.setUtwory((List<Utwor>) o.get("utwory"));
            plyty.add(p);
        }
        log.log(Level.INFO, "Zapytanie wykonane poprawnie");
    } catch (Exception e) {
        log.log(Level.SEVERE, "Blad wykonania zapytania");
    }
    return plyty;
}

From source file:com.mycompany.bean.PlytaService.java

public List<Plyta> searchByGatunek(String DBName, String CollectionName, String paramGatunek) throws Exception {
    List<Plyta> plyty = new ArrayList();
    try {/* www. j av  a2s . com*/
        DBCollection collection = getConnection(DBName, CollectionName);
        BasicDBObject GatunekIndex = new BasicDBObject();
        GatunekIndex.put("gatunek", 1);
        collection.createIndex(GatunekIndex, "IndexGatunek");
        BasicDBObject query = new BasicDBObject();
        query.append("gatunek", paramGatunek);
        DBCursor cur = collection.find(query);
        DBObject o;
        Plyta p;
        while (cur.hasNext()) {
            p = new Plyta();
            o = cur.next();
            p.setTytul((String) o.get("tytul"));
            p.setAutor((List<String>) o.get("autor"));
            p.setLiczbaUtworow((Integer) o.get("liczbaUtworow"));
            p.setWytwornia((List<String>) o.get("wytwornia"));
            p.setRokWydania((Integer) o.get("rokWydania"));
            p.setProducent((String) o.get("producent"));
            p.setGatunek((List<String>) o.get("gatunek"));
            p.setDlugosc((String) o.get("dlugosc"));
            p.setSingle((List<String>) o.get("single"));
            p.setNagrody((List<String>) o.get("nagrody"));
            p.setRodzajAlbumu((String) o.get("rodzajAlbumu"));
            p.setUtwory((List<Utwor>) o.get("utwory"));
            plyty.add(p);
        }
        log.log(Level.INFO, "Zapytanie wykonane poprawnie");
    } catch (Exception e) {
        log.log(Level.SEVERE, "Blad wykonania zapytania");
    }
    return plyty;
}

From source file:com.mycompany.bean.PlytaService.java

public List<Plyta> searchByUtwor(String DBName, String CollectionName, String paramUtwor) throws Exception {
    List<Plyta> plyty = new ArrayList();
    try {//from w  ww .j  av a  2  s. co m
        DBCollection collection = getConnection(DBName, CollectionName);
        BasicDBObject UtworIndex = new BasicDBObject();
        UtworIndex.put("utwory.nazwa", 1);
        collection.createIndex(UtworIndex, "IndexUtwor"); // tworzy index jeeli takiego nie ma
        BasicDBObject query = new BasicDBObject();
        query.append("utwory.nazwa", paramUtwor);
        DBCursor cur = collection.find(query);
        DBObject o;
        Plyta p;
        while (cur.hasNext()) {
            p = new Plyta();
            o = cur.next();
            p.setTytul((String) o.get("tytul"));
            p.setAutor((List<String>) o.get("autor"));
            p.setLiczbaUtworow((Integer) o.get("liczbaUtworow"));
            p.setWytwornia((List<String>) o.get("wytwornia"));
            p.setRokWydania((Integer) o.get("rokWydania"));
            p.setProducent((String) o.get("producent"));
            p.setGatunek((List<String>) o.get("gatunek"));
            p.setDlugosc((String) o.get("dlugosc"));
            p.setSingle((List<String>) o.get("single"));
            p.setNagrody((List<String>) o.get("nagrody"));
            p.setRodzajAlbumu((String) o.get("rodzajAlbumu"));
            p.setUtwory((List<Utwor>) o.get("utwory"));
            plyty.add(p);
        }
        log.log(Level.INFO, "Zapytanie wykonane poprawnie");
    } catch (Exception e) {
        log.log(Level.SEVERE, "Blad wykonania zapytania");
    }
    return plyty;
}

From source file:com.mysema.query.mongodb.MongodbQuery.java

License:Apache License

protected DBCursor createCursor(DBCollection collection, @Nullable Predicate where, QueryModifiers modifiers,
        List<OrderSpecifier<?>> orderBy) {
    DBCursor cursor = collection.find(createQuery(where));
    if (modifiers.getLimit() != null) {
        cursor.limit(modifiers.getLimit().intValue());
    }/* w  w w  .ja  v a2s .co  m*/
    if (modifiers.getOffset() != null) {
        cursor.skip(modifiers.getOffset().intValue());
    }
    if (orderBy.size() > 0) {
        cursor.sort(serializer.toSort(orderBy));
    }
    return cursor;
}

From source file:com.mythesis.userbehaviouranalysis.RequestServlet.java

License:Apache License

/**
 * Handles the HTTP <code>GET</code> method.
 * @param request servlet request/*from w  ww .j  a  v  a 2 s .  com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String userPath = request.getServletPath();
    String params = request.getQueryString().split("=")[1];
    System.out.println("I'm going to send the analysis to " + request.getQueryString());

    if (userPath.equals("/analysis")) {
        Mongo mongo = new Mongo("localhost", 27017);
        DB db = mongo.getDB("profileAnalysis");
        DBCollection userinfo = db.getCollection("history");
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("userID", params);
        DBCursor cursor = userinfo.find(searchQuery);
        if (cursor.hasNext()) {
            String entry = cursor.next().toString();
            System.out.println(entry);
            response.setHeader("Access-Control-Request-Method", "GET");
            response.setContentType("application/json");
            response.getWriter().write(entry);
        }
    }

}

From source file:com.mythesis.userbehaviouranalysis.RequestServlet.java

License:Apache License

/**
 * Handles the HTTP <code>POST</code> method.
 * @param request servlet request//  ww  w  . jav a  2 s  . c  om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String userPath = request.getServletPath();
    File input = new File("D://UserBehaviourAnalysisInput.txt");
    ProfileAnalysis analysis = new ProfileAnalysis();
    switch (userPath) {
    // if history is sent
    case "/history":
        String id = request.getParameter("userID");
        String[] urls = request.getParameter("urls").split(",");

        Mongo mongo = new Mongo("localhost", 27017);
        DB db = mongo.getDB("profileAnalysis");
        DBCollection userinfo = db.getCollection("userinfo");
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("userID", id);
        DBCursor cursor = userinfo.find(searchQuery);
        if (cursor.hasNext()) {
            DateTime current = new DateTime();
            SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
            DBObject entry = cursor.next();
            String check = (String) entry.get("timestamp");
            Date temp = null;
            try {
                temp = format.parse(check);
            } catch (ParseException ex) {
                Logger.getLogger(RequestServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
            DateTime previous = new DateTime(temp);
            System.out.println("last history analysis on: " + previous);
            System.out.println("current date/time: " + current);
            Duration duration = new Duration(previous, current);
            if (duration.getStandardHours() < 24)
                break;
        }
        analysis.perform(id, urls, input);
        break;
    // if query is sent    
    case "/query":
        try {
            JSONObject data = new JSONObject(request.getParameter("data"));
            Iterator it = data.keys();

            ArrayList<String> profiles = new ArrayList<>();
            ArrayList<String> queries = new ArrayList<>();
            while (it.hasNext()) {
                String key = (String) it.next();
                profiles.add(key);
                queries.add((String) data.get(key));
            }
            analysis.storeQueries(profiles, queries, input);
        } catch (JSONException ex) {
            Logger.getLogger(RequestServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        break;
    }
}

From source file:com.nlp.twitterstream.MongoUtil.java

License:Open Source License

/**
 * Get document list based on query//from   w w  w .  j  a v a2s .co m
 * 
 * @param collection
 * @param query
 * @return List<DBObject>
 */
public List<DBObject> getDocuments(DBCollection collection, BasicDBObject query) {

    List<DBObject> dbObjList = new ArrayList<DBObject>();

    // Get cursor on documents
    DBCursor cursor = collection.find(query);

    try {
        while (cursor.hasNext()) {
            dbObjList.add(cursor.next());
        }
    } finally {
        cursor.close();
    }

    return dbObjList;
}

From source file:com.openbravo.data.loader.MongoDBPreparedSentence.java

@Override
public DataResultSet openExec(Object params) throws BasicException {
    closeExec();// w  w  w  . j  ava 2s  .  c o m

    DBCollection collection = m_s.getMongoDBDatabase().getCollection(m_collectionName);

    if (m_SerWrite != null) {
        if (m_insert)
            m_SerWrite.writeValues(new MongoDBPreparedSentencePars(m_insertDBObject, m_writeParamColumnMap),
                    params);
        else if (m_find)
            m_SerWrite.writeValues(new MongoDBPreparedSentencePars(m_findDBObject, m_writeParamColumnMap),
                    params);
        else if (m_update)
            m_SerWrite.writeValues(new MongoDBPreparedSentencePars(m_updateDBObject, m_writeParamColumnMap),
                    params);
    }

    if (!m_nullColumn.isEmpty())
        m_findDBObject.append(m_nullColumn, new BasicDBObject("$exists", true));

    if (m_lessThanColumn != null) {
        for (int i = 0; i < m_lessThanColumn.length; ++i) {
            Object lessThanValue = m_findDBObject.get(m_lessThanColumn[i]);
            m_findDBObject.removeField(m_lessThanColumn[i]);
            m_findDBObject.append(m_lessThanColumn[i], new BasicDBObject("$lt", lessThanValue));
        }
    }

    if (m_greaterThanColumn != null) {
        for (int i = 0; i < m_greaterThanColumn.length; ++i) {
            Object greaterThanValue = m_findDBObject.get(m_greaterThanColumn[i]);
            m_findDBObject.removeField(m_greaterThanColumn[i]);
            m_findDBObject.append(m_greaterThanColumn[i], new BasicDBObject("$gt", greaterThanValue));
        }
    }

    // Insert statement
    if (m_insert) {
        collection.insert(m_insertDBObject);
    } else if (m_find) {

        if (!m_sortColumn.isEmpty()) {
            m_dbCursor = collection.find(m_findDBObject).sort(new BasicDBObject(m_sortColumn, 1));
            return new MongoDBDataResultSet(m_dbCursor, m_readParamColumnMap, m_SerRead);
        }

        if (!m_maxColumn.isEmpty()) {
            Iterator<DBObject> it = collection
                    .aggregate(new BasicDBObject("$match", m_findDBObject),
                            new BasicDBObject("$group",
                                    new BasicDBObject("_id", "null").append("MAX",
                                            new BasicDBObject("$max", "$" + m_maxColumn))))
                    .results().iterator();
            //Iterator<DBObject> it = collection.aggregate(new BasicDBObject("$group", new BasicDBObject("_id", "null").append("MAX", new BasicDBObject("$max", "$" + m_maxColumn)))).results().iterator();
            DBObject maxObject = new BasicDBObject();
            if (it.hasNext())
                maxObject = it.next();
            return new MongoDBDataResultSet(maxObject, m_readParamColumnMap, m_SerRead);
        }

        if (m_countAll) {
            Iterator<DBObject> it = collection
                    .aggregate(new BasicDBObject("$match", m_findDBObject), new BasicDBObject("$group",
                            new BasicDBObject("_id", "null").append("COUNT", new BasicDBObject("$sum", 1))))
                    .results().iterator();
            //Iterator<DBObject> it = collection.aggregate(new BasicDBObject("$group", new BasicDBObject("_id", "null").append("MAX", new BasicDBObject("$max", "$" + m_maxColumn)))).results().iterator();
            DBObject maxObject = new BasicDBObject();
            if (it.hasNext())
                maxObject = it.next();
            return new MongoDBDataResultSet(maxObject, m_readParamColumnMap, m_SerRead);
        }
        m_dbCursor = collection.find(m_findDBObject);
        return new MongoDBDataResultSet(m_dbCursor, m_readParamColumnMap, m_SerRead);
    } else if (m_update) {
        String findKey = ((String) m_writeParamColumnMap
                .get((Integer) m_writeParamColumnMap.keySet().toArray()[m_writeParamColumnMap.size() - 1]));
        String key = findKey.replace('s', ' ').trim();
        m_findDBObject.append(key, m_updateDBObject.get(findKey));

        // Remove the find criteria in the update object
        m_updateDBObject.remove(m_writeParamColumnMap
                .get((Integer) m_writeParamColumnMap.keySet().toArray()[m_writeParamColumnMap.size() - 1]));
        collection.findAndModify(m_findDBObject, null, null, true, m_updateDBObject, true, true);
        return new SentenceUpdateResultSet(0);
    }
    return null;
}

From source file:com.petpet.c3po.dao.mongo.MongoPersistenceLayer.java

License:Apache License

/**
 * {@inheritDoc}/*  w w  w .j  a  v a 2  s .  co m*/
 */
@Override
public <T extends Model> Iterator<T> find(Class<T> clazz, Filter filter) {

    DBObject query = this.getCachedFilter(filter);
    LOG.debug("Finding objects with the query:");
    LOG.debug(query.toString());
    String debugString = query.toString();
    DBCollection dbCollection = this.getCollection(clazz);
    MongoModelDeserializer modelDeserializer = this.getDeserializer(clazz);

    if (dbCollection == null) {
        LOG.warn("No collection found for clazz [{}]", clazz.getName());
        return new MongoIterator<T>(modelDeserializer, null);
    }

    DBCursor cursor = dbCollection.find(query);

    return new MongoIterator<T>(modelDeserializer, cursor);
}