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:buysell.shopping.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    // TODO add your handling code here:

    try {/*from www. jav  a2  s  .  com*/
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        DB db = mongoClient.getDB("buysale");
        System.out.println("Connect to database successfully");
        DBCollection coll = db.getCollection("assetes");
        System.out.println("Collection created successfully");
        //String name = jTextField1.getText().toString();
        //String email = jTextField2.getText().toString();
        //String phoneno = jTextField3.getText().toString();
        // String price= jTextField4.getText().toString();
        //String photourl = jTextField5.getText().toString();
        String check = jCheckBox1.getText().toString();
        System.out.println(check);
        String type = jComboBox1.getSelectedItem().toString();
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("type", type);
        DBCursor cursor = coll.find(searchQuery);
        int i = 0;
        while (cursor.hasNext() && i != 1) {
            i++;
            DBObject obj = cursor.next();
            String name = (String) obj.get("name");
            String email = (String) obj.get("email");
            String phoneno = (String) obj.get("phoneno");
            String price = (String) obj.get("price");
            String url = (String) obj.get("photourl");
            jTextField1.setText(name);
            jTextField2.setText(email);
            jTextField3.setText(phoneno);
            jTextField4.setText(price);
            jLabel3.setIcon(new javax.swing.ImageIcon(url));
        }

        System.out.println("Document inserted successfully");
    } catch (NumberFormatException e) {
        System.out.println();
    }
}

From source file:buysell.subads.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    try {//from   w  w w . j av a 2  s  .c o  m
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        DB db = mongoClient.getDB("buysale");
        System.out.println("Connect to database successfully");
        DBCollection coll = db.getCollection("assetes");
        System.out.println("Collection created successfully");
        String name = jTextField1.getText().toString();
        String email = jTextField2.getText().toString();
        String phoneno = jTextField3.getText().toString();
        String price = jTextField4.getText().toString();
        String photourl = jTextField5.getText().toString();
        String type = jComboBox1.getSelectedItem().toString();
        DB dB = mongoClient.getDB("snehal");
        System.out.println("Connect to database successfully");
        DBCollection colle = dB.getCollection("user");
        System.out.println("Collection created successfully");
        String uname = jTextField6.getText().toString();
        String passwd = jPasswordField1.getText().toString();
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("name", uname);
        searchQuery.put("passwd", passwd);

        DBCursor cursor = colle.find(searchQuery);
        int i = 0;
        while (cursor.hasNext()) {
            i = 1;
            System.out.println(cursor.next());
        }
        if (i == 0) {
            JOptionPane.showMessageDialog(null, "user name or passwod is wrong");

        } else {
            if (jTextField2.getText().length() != 0 && jTextField3.getText().length() != 0
                    && jTextField4.getText().length() != 0 && jTextField1.getText().length() != 0
                    && jTextField5.getText().length() != 0) {

                BasicDBObject doc = new BasicDBObject("name", name).append("username", uname)
                        .append("passwd", passwd).append("email", email).append("phoneno", phoneno)
                        .append("price", price).append("type", type).append("photourl", photourl);

                coll.insert(doc);
                home h2 = new home();
                h2.setVisible(true);
                dispose();
                System.out.println("Document inserted successfully");
            } else {
                JOptionPane.showMessageDialog(null, "enter the every field");
            }
        }

    } catch (NumberFormatException e) {
        System.out.println();
    }
}

From source file:calliope.core.database.MongoConnection.java

License:Open Source License

/**
 * Get a list of docIDs or file names corresponding to the regex expr
 * @param collName the collection to query
 * @param expr the regular expression to match against docid
 * @param key the key to retrieve for each matching document
 * @return an array of matching docids, which may be empty
 *///from ww w .ja va2s . c o m
@Override
public String[] listDocuments(String collName, String expr, String key) throws DbException {
    try {
        try {
            connect();
        } catch (Exception e) {
            throw new DbException(e);
        }
        DBCollection coll = getCollectionFromName(collName);
        if (coll != null) {
            BasicDBObject q = new BasicDBObject();
            q.put(JSONKeys.DOCID, Pattern.compile(expr));
            DBCursor curs = coll.find(q);
            ArrayList<String> docids = new ArrayList<String>();
            Iterator<DBObject> iter = curs.iterator();
            int i = 0;
            while (iter.hasNext()) {
                Object kId = iter.next().get(key);
                if (kId != null)
                    docids.add(kId.toString());
            }
            String[] array = new String[docids.size()];
            docids.toArray(array);
            return array;
        } else
            throw new DbException("collection " + collName + " not found");
    } catch (Exception e) {
        throw new DbException(e);
    }
}

From source file:calliope.db.MongoConnection.java

License:Open Source License

/**
 * Get a list of docIDs or file names corresponding to the regex expr
 * @param collName the collection to query
 * @param expr the regular expression to match against docid
 * @return an array of matching docids, which may be empty
 */// w ww  .ja  v a2s  .c  o m
@Override
public String[] listDocuments(String collName, String expr) throws AeseException {
    try {
        connect();
        DBCollection coll = getCollectionFromName(collName);
        if (coll != null) {
            BasicDBObject q = new BasicDBObject();
            q.put(JSONKeys.DOCID, Pattern.compile(expr));
            DBCursor curs = coll.find(q);
            ArrayList<String> docids = new ArrayList<String>();
            Iterator<DBObject> iter = curs.iterator();
            int i = 0;
            while (iter.hasNext()) {
                String dId = (String) iter.next().get(JSONKeys.DOCID);
                if (dId.matches(expr))
                    docids.add(dId);
            }
            String[] array = new String[docids.size()];
            docids.toArray(array);
            return array;
        } else
            throw new AeseException("collection " + collName + " not found");
    } catch (Exception e) {
        throw new AeseException(e);
    }
}

From source file:ch.agent.crnickl.mongodb.ReadMethodsForProperty.java

License:Apache License

/**
 * Find a collection of properties with names matching a pattern.
 * If the pattern is enclosed in slashes it is taken as a standard
 * regexp pattern; the slashes will be removed. If it is not enclosed
 * in slashes, it is taken as a minimal pattern and all occurrences of
 * "*" will be replaced with ".*" (zero or more arbitrary characters). 
 * /*from   w  w w  . ja v a 2  s .co  m*/
 * @param database a database
 * @param pattern a simple pattern or a regexp pattern
 * @return a collection of properties, possibly empty, never null
 * @throws T2DBException
 */
public Collection<Property<?>> getProperties(Database database, String pattern) throws T2DBException {
    try {
        DBCollection coll = getMongoDB(database).getProperties();
        DBObject query = null;
        if (pattern != null && pattern.length() > 0) {
            String regexp = extractRegexp(pattern);
            if (regexp == null)
                pattern = pattern.replace("*", ".*");
            else
                pattern = regexp;
            query = mongoObject(MongoDatabase.FLD_PROP_NAME, Pattern.compile(pattern));
        }
        DBCursor cursor = coll.find(query);
        Collection<Property<?>> result = new ArrayList<Property<?>>();
        try {
            while (cursor.hasNext()) {
                result.add(unpack(database, (BasicDBObject) cursor.next()));
            }
        } finally {
            cursor.close();
        }
        return result;
    } catch (Exception e) {
        throw T2DBMsg.exception(e, E.E20106, pattern);
    }
}

From source file:ch.agent.crnickl.mongodb.ReadMethodsForSchema.java

License:Apache License

/**
 * Find a collection of schema surrogates with labels matching a pattern.
 * // w w w  .  j av a2  s.c  om
 * @param db a database
 * @param pattern a simple pattern where "*" stands for zero or more characters
 * @return a collection of schema surrogates
 * @throws T2DBException
 */
public Collection<Surrogate> getSchemaSurrogateList(Database db, String pattern) throws T2DBException {
    try {
        Collection<Surrogate> result = new ArrayList<Surrogate>();
        DBCollection coll = getMongoDB(db).getSchemas();
        DBObject query = null;
        if (pattern != null && pattern.length() > 0) {
            String regexp = extractRegexp(pattern);
            if (regexp == null) {
                regexp = pattern.replace("*", ".*");
                if (regexp.equals(pattern))
                    regexp = null;
            }
            query = mongoObject(MongoDatabase.FLD_SCHEMA_NAME,
                    regexp == null ? pattern : Pattern.compile(regexp));
        }
        DBCursor cursor = coll.find(query);
        try {
            while (cursor.hasNext()) {
                ObjectId id = (ObjectId) cursor.next().get(MongoDatabase.FLD_ID);
                Surrogate s = makeSurrogate(db, DBObjectType.SCHEMA, new MongoDBObjectId(id));
                result.add(s);
            }
        } finally {
            cursor.close();
        }
        return result;
    } catch (Exception e) {
        throw T2DBMsg.exception(e, E.E30105, pattern);
    }
}

From source file:ch.windmobile.server.mongo.MongoDataSource.java

License:Open Source License

private List<BasicDBObject> getHistoricData(String stationId, DateTime lastUpdate, int duration) {
    DBCollection dataCollection = database.getCollection(getDataCollectionName(stationId));
    long startTime = lastUpdate.getMillis() - duration * 1000;
    DBObject query = BasicDBObjectBuilder
            .start("_id", BasicDBObjectBuilder.start("$gte", startTime / 1000).get()).get();

    List<BasicDBObject> datas = new ArrayList<BasicDBObject>();
    DBCursor cursor = dataCollection.find(query);
    while (cursor.hasNext()) {
        datas.add((BasicDBObject) cursor.next());

    }/*from ww w . j  a  v a2s. co m*/
    return datas;
}

From source file:ch.windmobile.server.mongo.MongoDataSource.java

License:Open Source License

@Override
public List<StationInfo> getStationInfoList(boolean allStation) throws DataSourceException {
    try {//from   w w  w  .jav a 2s.  co m
        DBCollection stations = database.getCollection(getStationsCollectionName());

        List<String> list = new ArrayList<String>();
        if (allStation == true) {
            list.add(Status.RED.value());
            list.add(Status.ORANGE.value());
            list.add(Status.GREEN.value());
        } else {
            list.add(Status.GREEN.value());
        }
        DBObject query = BasicDBObjectBuilder.start("prov", getProvider())
                .add("status", new BasicDBObject("$in", list)).get();
        DBCursor cursor = stations.find(query);

        List<StationInfo> stationInfoList = new ArrayList<StationInfo>();
        while (cursor.hasNext()) {
            try {
                BasicDBObject stationJson = (BasicDBObject) cursor.next();
                if (getStationsFilter() != null) {
                    String stationId = stationJson.getString("_id");
                    if (getStationsFilter().contains(stationId)) {
                        stationInfoList.add(createStationInfo(stationJson));
                    }
                } else {
                    stationInfoList.add(createStationInfo(stationJson));
                }
            } catch (Exception e) {
                log.warn("Station was ignored because:", e);
            }
        }

        return stationInfoList;
    } catch (Exception e) {
        throw exceptionHandler(e);
    }
}

From source file:cl.wsconsulta.consulta.Consulta.java

@WebMethod(operationName = "consultar")
public String realizarConsulta(@WebParam(name = "consulta") BasicDBList privileges) throws IOException {
    DB database;/*from  ww  w  .j  ava2s  . c om*/
    try (BufferedReader entrada = new BufferedReader(new FileReader("datos.ini"))) {
        database = null;
        try {
            dataBase = entrada.readLine();
            indiceInvertido = entrada.readLine();
            coleccionDocumentos = entrada.readLine();
            coleccionIndice = entrada.readLine();

            MongoClient mongoClient = new MongoClient();
            database = mongoClient.getDB(dataBase);

        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }
        entrada.close();
    }

    DBCollection indiceInvertido = database.getCollection(coleccionIndice);
    DBCollection documento = database.getCollection(coleccionDocumentos);

    while (true) {

        BufferedReader lector = new BufferedReader(new InputStreamReader(System.in));
        String consulta = lector.readLine().toUpperCase();
        BasicDBObject query = new BasicDBObject("palabra", consulta);
        DBCursor cursor = indiceInvertido.find(query);
        if (cursor.count() == 0) {
            System.out.println("Busqueda sin resultados: " + consulta);
        } else {
            while (cursor.hasNext()) {
                privileges = (BasicDBList) cursor.next().get("documento");
                //DBObject obj = cursor.next();
                //Object value = obj.get("documento");
                //System.out.println(value);
            }
            System.out.println(privileges);
        }
    }

}

From source file:cl.wsconsulta.servlet.ConsultaServlet.java

public static String consultar(String consulta) throws FileNotFoundException, IOException {

    DB database;//w  w  w  . jav a  2  s .c o  m

    database = null;

    dataBase = "labsd";
    indiceInvertido = "prueba.xml";
    coleccionDocumentos = "documentos";
    coleccionIndice = "indiceInvertido";

    MongoClient mongoClient = new MongoClient();
    database = mongoClient.getDB(dataBase);

    DBCollection indiceInvertido = database.getCollection(coleccionIndice);
    DBCollection documento = database.getCollection(coleccionDocumentos);
    BasicDBList privileges = new BasicDBList();

    BasicDBObject query = new BasicDBObject("palabra", consulta);
    DBCursor cursor = indiceInvertido.find(query);
    if (cursor.count() == 0) {
        System.out.println("Busqueda sin resultados: " + consulta);
    } else {
        while (cursor.hasNext()) {

            privileges = (BasicDBList) cursor.next().get("documento");

            //DBObject obj = cursor.next();
            //Object value = obj.get("documento");
            //System.out.println(value);
        }
    }
    String lista = privileges.toString();
    return lista;

}