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() 

Source Link

Document

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

Usage

From source file:com.miya.twit.mongodb.DBConnectSentiment.java

public ArrayList getTwitterFindAll() {
    ArrayList arr = new ArrayList();
    DBCollection collection = dbConnection();
    DBCursor cursor = collection.find();
    try {/*from   ww w  .  ja va2s  .com*/
        String str = "";
        while (cursor.hasNext()) {
            str = cursor.curr().get("text").toString();
            arr.add(str);
        }
    } finally {
        cursor.close();
    }

    return arr;

}

From source file:com.miya.twit.mongodb.DBConnectSentiment.java

public void getTweetWithUserId(int userId) {

    DBCollection collection = dbConnection();
    if (collection != null) {

        DBCursor cursor = collection.find();
        try {/*w ww. j a v  a 2s  .c  o  m*/
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }
        //------------------------------------

        // get documents by query
        BasicDBObject query = new BasicDBObject("userid", new BasicDBObject("$gt", userId));

        cursor = collection.find(query);
        System.out.println("twit bulundu : " + cursor.count());

        //
        //            /**
        //             * ** Update ***
        //             */
        //            //update documents found by query "age > 30" with udpateObj "age = 20"
        //            BasicDBObject newDocument = new BasicDBObject();
        //            newDocument.put("age", 20);
        //
        //            BasicDBObject updateObj = new BasicDBObject();
        //            updateObj.put("$set", newDocument);
        //
        //            collection.update(query, updateObj, false, true);
        //
        //            /**
        //             * ** Find and display ***
        //             */
        //            cursor = collection.find(query);
        //            System.out.println("Person with age > 40 after update --> " + cursor.count());
        //
        //
        //            //get all again
        //            cursor = collection.find();
        //            try {
        //                while (cursor.hasNext()) {
        //                    System.out.println(cursor.next());
        //                }
        //            } finally {
        //                cursor.close();
        //            }
    }

}

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

public List<Plyta> getCollenction(String dbName, String colName) throws Exception {
    DBCollection collection = getConnection(dbName, colName);
    DBCursor cur = collection.find();
    List<Plyta> plyty = new ArrayList();
    //List<String> autorzy;
    DBObject o;/*from ww  w  .  jav a2 s.c o m*/
    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);
    }
    return plyty;
}

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

License:Open Source License

/**
 * Get all documents in collection//from  w ww  .j av a2 s  .c o  m
 * 
 * @param collection
 */
public List<DBObject> getAllDocuments(DBCollection collection) {

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

    DBCursor cursor = collection.find();
    try {
        while (cursor.hasNext()) {
            dbObjList.add(cursor.next());
        }
    } finally {
        cursor.close();
    }

    return dbObjList;
}

From source file:com.pavel.testtask.highway.MongoInitionalizer.java

@Override
public Set<Gate> getEnterPoints() {
    DBCollection table = db.getCollection("EnterPoint");
    DBCursor cur = table.find();
    List<DBObject> pointList = cur.toArray();

    Set<Gate> enterPointsSet = new HashSet<>();
    for (DBObject drv : pointList) {
        Gate d = new Gate((String) drv.get("name"), (float) ((int) drv.get("distance")));
        enterPointsSet.add(d);//from   w  ww.  java2  s . co m
    }
    return enterPointsSet;
}

From source file:com.pavel.testtask.highway.MongoInitionalizer.java

@Override
public Set<Driver> getRegistredDrivers() {
    DBCollection table = db.getCollection("Driver");
    DBCursor cur = table.find();
    List<DBObject> driverList = cur.toArray();

    Set<Driver> driversSet = new HashSet<>();

    for (DBObject drv : driverList) {
        driversSet.add(new Driver((int) drv.get("id"), (String) drv.get("email")));
    }/*w  w w .ja va  2 s. c o  m*/
    return driversSet;
}

From source file:com.sample.MyGroceryListServlet.java

License:Open Source License

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *///w  w w .  ja  v a2 s.  c  o  m
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Reference: http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/#getting-started-with-java-driver

    String envVars = System.getenv("VCAP_SERVICES");

    DBObject dbO = (DBObject) JSON.parse(envVars);
    String parsedString = dbO.get("mongodb").toString();

    // Remove trailing and starting array brackets (otherwise it won't be valid JSON)
    parsedString = parsedString.replaceFirst("\\[ ", "");
    parsedString = parsedString.replaceFirst("\\]$", "");

    // Get the credentials
    dbO = (DBObject) JSON.parse(parsedString);
    parsedString = dbO.get("credentials").toString();

    // For debugging only
    // System.out.println(parsedString);

    dbO = (DBObject) JSON.parse(parsedString);

    System.out.println("Host name : " + dbO.get("hostname"));
    String hostName = dbO.get("hostname").toString();
    int port = Integer.parseInt(dbO.get("port").toString());
    String dbName = dbO.get("db").toString();
    String userName = dbO.get("username").toString();
    String password = dbO.get("password").toString();

    Mongo mongoClient = new Mongo(hostName, port);

    DB db = mongoClient.getDB(dbName);
    db.authenticate(userName, password.toCharArray());

    // Clean up old entries
    DBCollection coll = db.getCollection("testCollection");
    coll.drop();

    BasicDBObject lastAddedObject = null;
    for (String curItem : myGroceryList) {
        lastAddedObject = new BasicDBObject("i", curItem);
        coll.insert(lastAddedObject);
    }
    response.getWriter().println("<b>My grocery list is:</b>");

    coll.remove(lastAddedObject);
    DBCollection loadedCollection = db.getCollection("testCollection");
    DBCursor cursor = loadedCollection.find();
    try {
        response.getWriter().println("<ul>");
        while (cursor.hasNext()) {
            response.getWriter().println("<li>" + cursor.next().get("i") + "</li>");
        }
        response.getWriter().println("</ul>");
    } finally {
        cursor.close();
    }
}

From source file:com.servlets.GetPhotosList.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from w  ww .  j  a v  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 {
    List<String> photoList = new ArrayList<>();
    String username;
    // check if the session exists
    HttpSession session = request.getSession(false);
    if (session == null || (username = (String) session.getAttribute("username")) == null) {
        sendResponse(response, "Invalid session.");
        return;
    }
    // check if up-to-date list has already been sent
    Date lastUpdatedList = (Date) session.getAttribute("lastUpdatedList");
    if (lastUpdatedList != null) {
        if (lastUpdatedList == (Date) session.getAttribute("lastSentList")) {
            // user already has up-to-date photos list
            sendResponse(response, "");
            return;
        }
    } else {
        lastUpdatedList = new Date();
        session.setAttribute("lastUpdatedList", lastUpdatedList);
    }
    // this stores all the data for a photo
    DBObject file;
    // this stores the creation date, the width and height of the photo
    DBObject metadata;
    String md5;
    DBCollection collection = db.getCollection(username + ".files");
    Date date;
    int width;
    int height;
    Cursor cursor = collection.find();
    // check if at least one photo is present
    if (!cursor.hasNext()) {
        sendResponse(response, "0");
        return;
    }
    while (cursor.hasNext()) {
        file = cursor.next();
        md5 = (String) file.get("md5");
        metadata = (DBObject) file.get("metadata");
        // extract date, width and height from the metadata object
        date = (Date) metadata.get("creationDate");
        width = (int) metadata.get("width");
        height = (int) metadata.get("height");
        // add the data retreived to the list to communicate to the client
        photoList.add(md5 + ',' + date.getTime() + ',' + width + ',' + height + (cursor.hasNext() ? '|' : ""));
    }
    String message = "";
    for (String s : photoList) {
        message += s;
    }
    session.setAttribute("lastSentList", lastUpdatedList);
    sendResponse(response, message);
}

From source file:com.sfelf.connectors.mongoOplogCursorConnector.java

License:Open Source License

/**
 * Returns a {@link BSONTimestamp} of either the timestamp in the specified log collection for the specified namespace or
 * the timestamp of the newest entry in the oplog.rs. 
 * /*from   w ww .ja v  a2 s  . com*/
 * @param oplog       The {@link DBCollection} containing the oplog (local.oplog.rs)
 * @param log          The {@link DBCollection} containing a log of the timestamp for the last entry processed for the specified namespace 
 * @param namespace      The namespace for which the last timestamp is being requested
 * @return {@link BSONTimestamp}
 * @throws MongoOplogCursorException
 */
private BSONTimestamp getLastTimestamp(DBCollection oplog, DBCollection log, String namespace)
        throws MongoOplogCursorException {
    BSONTimestamp lastTimestamp = null;

    if (log != null) {
        DBObject queryParams = new BasicDBObject("_id", namespace);
        DBObject result = log.findOne(queryParams);
        if (result != null && result.get(LAST_TIMESTAMP_LOG_FIELD) != null) {
            lastTimestamp = (BSONTimestamp) result.get(LAST_TIMESTAMP_LOG_FIELD);
        }
    }
    if (lastTimestamp == null) {
        DBObject orderBy = new BasicDBObject("$natural", SORT_ORDER_DESCENDING);
        DBCursor cursor = oplog.find().sort(orderBy);
        if (cursor.hasNext()) {
            lastTimestamp = (BSONTimestamp) cursor.next().get("ts");
        } else {
            throw new MongoOplogCursorException("Unable to establish cursor as the oplog is empty");
        }
    }
    return lastTimestamp;
}

From source file:com.sitewhere.mongodb.user.MongoUserManagement.java

License:Open Source License

public List<IGrantedAuthority> listGrantedAuthorities(IGrantedAuthoritySearchCriteria criteria)
        throws SiteWhereException {
    DBCollection auths = getMongoClient().getAuthoritiesCollection();
    DBCursor cursor = auths.find().sort(new BasicDBObject(MongoGrantedAuthority.PROP_AUTHORITY, 1));
    List<IGrantedAuthority> matches = new ArrayList<IGrantedAuthority>();
    try {// w w  w.  j av a  2s  .  c  om
        while (cursor.hasNext()) {
            DBObject match = cursor.next();
            matches.add(MongoGrantedAuthority.fromDBObject(match));
        }
    } finally {
        cursor.close();
    }
    return matches;
}