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.fpt.xml.hth.db.lib.DAO.MovieDAO.java

public List<MovieTheaterSessionDTO> getAll() {
    connection();// ww  w . j  a  v  a  2  s. co  m
    List<MovieTheaterSessionDTO> lst = new ArrayList<MovieTheaterSessionDTO>();
    DBCollection collection = movieCollection;
    DBCursor cursor = collection.find();
    while (cursor.hasNext()) {
        BasicDBObject basic = (BasicDBObject) cursor.next();
        MovieTheaterSessionDTO movieDto = converter.convertBasicObjectToModel(basic);
        lst.add(movieDto);
    }
    cursor.close();
    mongoClient.close();
    return lst;
}

From source file:com.fuction.MongoDB.java

public static void display() {
    try {/* w  w w .ja  va2  s .  co m*/
        Mongo mongo = new Mongo(HOST, PORT);
        DB db = mongo.getDB(DB);
        DBCollection collection = db.getCollection("Data");
        System.out.println("Collection mycol selected successfully");
        DBCursor cursor = collection.find();
        int i = 1;
        while (cursor.hasNext()) {
            System.out.println("Inserted Document: " + i);
            String jsonString = cursor.next().toString();
            System.out.println(jsonString);
            JSONObject jsonObject = parseJSONObject(jsonString);
            System.out.println(jsonObject.get("Area"));
            i++;
        }
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.fuction.MongoDB.java

public static ArrayList<InformationObj> getObj() {
    ArrayList<InformationObj> list = new ArrayList<>();
    try {/*  www .j a v  a 2s.co  m*/
        Mongo mongo = new Mongo(HOST, PORT);
        DB db = mongo.getDB(DB);
        DBCollection collection = db.getCollection("Data");
        System.out.println("Collection mycol selected successfully");
        DBCursor cursor = collection.find();
        while (cursor.hasNext()) {
            String jsonString = cursor.next().toString();
            //System.out.println(jsonString);
            JSONObject jsonObject = parseJSONObject(jsonString);

            String roomNumber = (String) jsonObject.get("RoomNumber");
            String area = (String) jsonObject.get("Area");
            String address = (String) jsonObject.get("Address");
            String direction = (String) jsonObject.get("Direction");
            String numberOfBedRooms = (String) jsonObject.get("NumberOfBedRooms");
            String numberOfBathRooms = (String) jsonObject.get("NumberOfBathRooms");
            String project = (String) jsonObject.get("Project");
            String floor = (String) jsonObject.get("Floor");
            String utilities = (String) jsonObject.get("Utilities");
            String environment = (String) jsonObject.get("Environment");
            String description = (String) jsonObject.get("Description");
            String pricePerMetreSquare = (String) jsonObject.get("PricePerMetreSquare");
            String price = (String) jsonObject.get("Price");
            String image = (String) jsonObject.get("Image");
            String city = (String) jsonObject.get("City");
            String district = (String) jsonObject.get("District");

            InformationObj iObj = new InformationObj(roomNumber, area, address, direction, numberOfBedRooms,
                    numberOfBathRooms, project, floor, utilities, environment, description, pricePerMetreSquare,
                    price, image, city, district);
            list.add(iObj);
        }
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        e.printStackTrace();
    }
    return list;
}

From source file:com.github.maasdi.mongo.wrapper.NoAuthMongoClientWrapper.java

License:Apache License

public List<MongoField> discoverFields(String db, String collection, String query, String fields,
        boolean isPipeline, int docsToSample) throws KettleException {
    DBCursor cursor = null;// w  ww  .j av  a  2 s.  co m
    try {
        int numDocsToSample = docsToSample;
        if (numDocsToSample < 1) {
            numDocsToSample = 100; // default
        }

        List<MongoField> discoveredFields = new ArrayList<MongoField>();
        Map<String, MongoField> fieldLookup = new HashMap<String, MongoField>();
        try {
            DB database = getDb(db);

            if (Const.isEmpty(collection)) {
                throw new KettleException(
                        BaseMessages.getString(PKG, "MongoNoAuthWrapper.ErrorMessage.NoCollectionSpecified")); //$NON-NLS-1$
            }
            DBCollection dbcollection = database.getCollection(collection);

            Iterator<DBObject> pipeSample = null;

            if (isPipeline) {
                pipeSample = setUpPipelineSample(query, numDocsToSample, dbcollection);
            } else {
                if (Const.isEmpty(query) && Const.isEmpty(fields)) {
                    cursor = dbcollection.find().limit(numDocsToSample);
                } else {
                    DBObject dbObject = (DBObject) JSON.parse(Const.isEmpty(query) ? "{}" //$NON-NLS-1$
                            : query);
                    DBObject dbObject2 = (DBObject) JSON.parse(fields);
                    cursor = dbcollection.find(dbObject, dbObject2).limit(numDocsToSample);
                }
            }

            int actualCount = 0;
            while (cursor != null ? cursor.hasNext() : pipeSample.hasNext()) {
                actualCount++;
                DBObject nextDoc = (cursor != null ? cursor.next() : pipeSample.next());
                docToFields(nextDoc, fieldLookup);
            }

            postProcessPaths(fieldLookup, discoveredFields, actualCount);

            return discoveredFields;
        } catch (Exception e) {
            throw new KettleException(e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    } catch (Exception ex) {
        if (ex instanceof KettleException) {
            throw (KettleException) ex;
        } else {
            throw new KettleException(
                    BaseMessages.getString(PKG, "MongoNoAuthWrapper.ErrorMessage.UnableToDiscoverFields"), ex); //$NON-NLS-1$
        }
    }
}

From source file:com.hangum.tadpole.importdb.core.dialog.importdb.utils.MongoDBQueryUtil.java

License:Open Source License

/**
 * ??  .//  ww w  . java  2s.co  m
 */
private void runSQLSelect() throws Exception {

    DBCollection dbCollection = MongoDBQuery.findCollection(userDB, requestQuery);
    DBCursor dbCursor = dbCollection.find().skip(startPoint).limit(DATA_COUNT);

    listDBOject = dbCursor.toArray();
}

From source file:com.hangum.tadpole.mongodb.core.test.ConvertJsonToDBObject.java

License:Open Source License

public static void main(String[] args) throws Exception {

    ConAndAuthentication testMongoCls = new ConAndAuthentication();
    Mongo mongo = testMongoCls.connection(ConAndAuthentication.serverurl, ConAndAuthentication.port);
    DB db = mongo.getDB("test");

    DBCollection myColl = db.getCollection("objectInsert");

    //      /* ww  w.jav  a2 s. c o  m*/
    //      DBObject dbObject = new BasicDBObject();
    //      dbObject.put("aa", 1);
    //      dbObject.put("bb", "33");

    DBObject dbObject = (DBObject) JSON.parse("{'rental_id':1,  'inventory_id':367}");
    myColl.insert(dbObject);

    DBCursor cursorDoc = myColl.find();
    while (cursorDoc.hasNext()) {
        System.out.println(cursorDoc.next());
    }

    System.out.println("Done");

}

From source file:com.hangum.tadpole.mongodb.core.test.MongoTestProfilling.java

License:Open Source License

/**
 * @param args//w ww.  j av a 2 s  .  c o  m
 */
public static void main(String[] args) throws Exception {
    ConAndAuthentication testMongoCls = new ConAndAuthentication();
    Mongo mongo = testMongoCls.connection(ConAndAuthentication.serverurl, ConAndAuthentication.port);
    DB db = mongo.getDB("test");

    // ??       
    System.out.println("####[profilling  ]######################################################");
    CommandResult cr = db.command(new BasicDBObject("profile", 0));

    System.out.println("[ok]" + cr.ok());
    if (!cr.ok())
        System.out.println("[Exception ]" + cr.getException().toString());
    System.out.println("[toString]" + JSONUtil.getPretty(cr.toString()));
    System.out.println("[size]" + cr.size());
    System.out.println("####[profilling  ]######################################################");

    //  ?          
    System.out.println(
            "####[profilling collections  ]######################################################");
    if (db.collectionExists("system.profile")) {
        DBCollection profileColl = db.getCollection("system.profile");
        profileColl.drop();
    }
    System.out.println(
            "####[profilling collections  ]######################################################");
    //  ?     

    // system.profile collection ? 
    System.out.println(
            "####[profilling collections ? ]######################################################");
    DBObject dbObject = (DBObject) JSON.parse("{capped:true, size:8000000}");
    DBCollection dbColl = db.createCollection("system.profile", dbObject);
    BasicDBObject newProfileColl = (BasicDBObject) dbColl.getStats().copy();
    System.out.println(
            "####[profilling collections ? ]######################################################");
    // system.profile collection ? 

    System.out.println("####[profilling ]######################################################");
    cr = db.command(new BasicDBObject("profile", 2));

    System.out.println("[ok]" + cr.ok());
    if (!cr.ok())
        System.out.println("[Exception ]" + cr.getException().toString());
    System.out.println("[toString]" + JSONUtil.getPretty(cr.toString()));
    System.out.println("[size]" + cr.size());
    System.out.println("####[profilling ]######################################################");

    //      //#######################################################################################################
    //      //#######################################################################################################
    //      //#######################################################################################################      
    System.out.println("####[start profilling result]######################################################");
    DBCollection myColl = db.getCollection("system.profile");

    BasicDBObject query = new BasicDBObject();
    query.put("millis", new BasicDBObject("$gt", 4));

    DBCursor myCursor = myColl.find();
    while (myCursor.hasNext()) {
        DBObject dbObj = myCursor.next();
        System.out.println(dbObj.get("ts") + " - " + dbObj.get("ns") + " - " + dbObj.get("nscanned") + "/"
                + dbObj.get("nreturned") + " millis :" + dbObj.get("millis"));
    }
    System.out.println("####[end profilling result]######################################################");

    mongo.close();
}

From source file:com.hangum.tadpole.mongodb.core.test.UpdateEx.java

License:Open Source License

public static void showCollection(DBCollection coll) {
    DBCursor cursorDocJSON = coll.find();
    while (cursorDocJSON.hasNext()) {
        System.out.println(cursorDocJSON.next());
    }/*from  w  w w.  j  a v a2s  . c  o m*/
}

From source file:com.ibm.bluemix.smartveggie.dao.SubOutletVendorAllocationDaoImpl.java

@Override
public List<BasicDBObject> retrieveAllocatedSubOutlet() {

    List<BasicDBObject> listDBObjects = null;
    try {/*from w ww .  j  a v a  2  s .  c o m*/
        System.out.println("Retrieving Allocated SubOutlets...");
        listDBObjects = new ArrayList<BasicDBObject>();
        DB db = MongodbConnection.getMongoDB();
        DBCollection col = db.getCollection(ICollectionName.COLLECTION_ALLOC_SUBOUTLETS);
        DBCursor cursor = col.find();
        BasicDBObject obj = null;
        while (cursor.hasNext()) {
            obj = (BasicDBObject) cursor.next();
            System.out.println("Retrieved: " + obj);
            listDBObjects.add(obj);
        }
        cursor.close();
    } catch (Exception e) {
        throw e;
    }
    return listDBObjects;
}

From source file:com.ikanow.infinit.e.api.knowledge.federated.SimpleFederatedQueryEngine.java

License:Open Source License

public void test_cacheExpire() {
    DBCollection endpointCacheCollection = getCacheCollection();

    DBCursor dbc = endpointCacheCollection.find();
    for (DBObject cacheEntryObj : dbc) {
        BasicDBObject cacheEntry = (BasicDBObject) cacheEntryObj;
        cacheEntry.put(SimpleFederatedCache.expiryDate_, new Date(new Date().getTime() - 3600L * 1000L)); // (ie expired an hour ago)
        endpointCacheCollection.save(cacheEntry);
    }//from  w w w.  j a  v a 2 s.  co  m
}