Example usage for com.mongodb DBCollection getCount

List of usage examples for com.mongodb DBCollection getCount

Introduction

In this page you can find the example usage for com.mongodb DBCollection getCount.

Prototype

public long getCount() 

Source Link

Document

Get the count of documents in collection.

Usage

From source file:Presentation.Bean.MenuBean.java

public ArrayList<Menu> getMenuList() {

    // To connect to mongo dbserver
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    // Now connect to your databases
    DB db = mongoClient.getDB("Restaurant");
    System.out.println("Connect to database successfully");

    DBCollection collection = db.getCollection("Menus");
    System.out.println("Collection menu selected successfully");

    // PASO 4.1: "CREATE" -> Metemos los objetos men (o documentos en Mongo) en la coleccion Menu
    for (Menu men : menuList) {
        collection.insert(men.toDBObjectMenu());
    }//from  w w  w . j ava2  s. c o  m

    // PASO 4.2.1: "READ" -> Leemos todos los documentos de la base de datos
    int numDocumentos = (int) collection.getCount();
    System.out.println("Nmero de documentos en la coleccin Menu: " + numDocumentos + "\n");

    // Busco todos los documentos de la coleccin y los imprimo
    DBCursor cursor = collection.find();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toString());
        }
    } finally {
        cursor.close();
    }

    return menuList;

}

From source file:tour.QuickTour.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 *//*from  w  w  w.  j a  v a2 s . c om*/
@SuppressWarnings("deprecation")
public static void main(final String[] args) {
    MongoClient mongoClient;

    if (args.length == 0) {
        // connect to the local database server
        mongoClient = new MongoClient();
    } else {
        mongoClient = new MongoClient(new MongoClientURI(args[0]));
    }

    // get handle to the "mydb" database
    DB db = mongoClient.getDB("mydb");

    // get a list of the collections in this database and print them out
    Set<String> collectionNames = db.getCollectionNames();
    for (final String s : collectionNames) {
        System.out.println(s);
    }

    // get a handle to the "test" collection
    DBCollection collection = db.getCollection("test");

    // drop all the data in it
    collection.drop();

    // make a document and insert it
    BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database").append("count", 1)
            .append("info", new BasicDBObject("x", 203).append("y", 102));

    collection.insert(doc);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    DBObject myDoc = collection.findOne();
    System.out.println(myDoc);

    // now, lets add lots of little documents to the collection so we can explore queries and cursors
    List<DBObject> documents = new ArrayList<DBObject>();
    for (int i = 0; i < 100; i++) {
        documents.add(new BasicDBObject().append("i", i));
    }
    collection.insert(documents);
    System.out.println(
            "total # of documents after inserting 100 small ones (should be 101) " + collection.getCount());

    // lets get all the documents in the collection and print them out
    DBCursor cursor = collection.find();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // now use a query to get 1 document out
    cursor = collection.find(new BasicDBObject("i", 71));

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // now use a range query to get a larger subset
    cursor = collection.find(new BasicDBObject("i", new BasicDBObject("$gt", 50)));

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // range query with multiple constraints
    cursor = collection.find(new BasicDBObject("i", new BasicDBObject("$gt", 20).append("$lte", 30)));

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // create an ascending index on the "i" field
    collection.createIndex(new BasicDBObject("i", 1));

    // list the indexes on the collection
    List<DBObject> list = collection.getIndexInfo();
    for (final DBObject o : list) {
        System.out.println(o);
    }

    // release resources
    mongoClient.close();
}

From source file:tourapi.TourAPI.java

private void MLUpdate(String from, String to) {
    // ?//w  w w .  j  a va  2s  .com
    //fromt->to 
    MongoClient mongoClient = getMongoClient();
    String result = null;
    try {
        DB db = mongoClient.getDB("my_database");
        DBCollection coll = db.getCollection("ML_Result");
        WriteConcern w = new WriteConcern(1, 0);
        mongoClient.setWriteConcern(w);

        DBObject doc = new BasicDBObject();
        // string?  select
        BasicDBObject query = new BasicDBObject();
        query.put("from", from);
        query.put("to", to);

        DBCursor cursor = coll.find(query);

        if (cursor.hasNext())// ?? 
        {
            DBObject mapObj = cursor.next();
            int num = ((Number) mapObj.get("num")).intValue();
            num++;
            BasicDBObject newDocument = new BasicDBObject();
            newDocument.append("$set", new BasicDBObject().append("num", num));
            BasicDBObject searchQuery = new BasicDBObject().append("from", from).append("to", to);
            coll.update(searchQuery, newDocument);
            cursor.close();
        } else {// ??  ? -> ?? insert
            doc.put("from", from);
            doc.put("to", to);
            doc.put("num", 1);
            coll.insert(doc);
            cursor.close();
        }
        System.out.println(coll.getCount());
        // close resources
        mongoClient.close();
    } catch (Exception e) {
        System.err.println("error evoke");
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

From source file:tourapi.TourAPI.java

private String convertTitleToId(String title, String url, int num) {
    String result = null;/* w w  w . j ava2s.  co  m*/
    try {

        // To connect to mongodb server
        MongoClient mongoClient = getMongoClient();
        DB db = mongoClient.getDB("my_database");
        DBCollection coll = db.getCollection("TB_titleID");
        System.out.println("? ");

        WriteConcern w = new WriteConcern(1, 0);
        mongoClient.setWriteConcern(w);
        // Now connect to your databases

        DBObject doc = new BasicDBObject();
        BasicDBObject query = new BasicDBObject("title", title);

        DBCursor cursor = coll.find(query);

        if (cursor.hasNext())// ?? 
        {
            result = cursor.next().get("ID").toString();
            cursor.close();
        } else {// ??  ? -> ?? insert
            int autoIncre = (int) coll.getCount();
            doc.put("ID", autoIncre);
            doc.put("title", title);
            System.out.println("URL : " + url);
            doc.put("url", url);
            doc.put("num", num);
            coll.insert(doc);
            cursor.close();
            result = autoIncre + "";
        }
        // close resources
        mongoClient.close();
    } catch (Exception e) {
        System.err.println("convertTitleToId error");
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
    return result;
}

From source file:tourapi.TourAPI.java

/**
 * @param args the command line arguments
 *//*ww  w  . ja  va  2s .  c o  m*/

private tour_Information findwithDB(String from) {

    tour_Information returntour = new tour_Information();
    String to = null;

    try {
        MongoClient mongoClient = getMongoClient();
        DB db = mongoClient.getDB("my_database");
        DBCollection coll = db.getCollection("ML_Result");
        WriteConcern w = new WriteConcern(1, 0);
        mongoClient.setWriteConcern(w);

        // string?  select
        BasicDBObject query = new BasicDBObject();
        query.put("from", from);

        DBCursor cursor = coll.find(query);
        cursor.sort(new BasicDBObject("num", -1));

        int num = -1;
        System.out.println("from 0: " + from);
        if (cursor.hasNext())// ??  
        {
            DBObject mapObj = cursor.next();
            String temp = mapObj.get("to").toString();
            num = Integer.parseInt(temp);
            //num = ((Number) mapObj.get("to")).intValue();
            cursor.close();

        } else {
            //System.out.println("from2 : "+from);
            returntour.myURL = null;
        }
        System.out.println(coll.getCount());
        // close resources
        if (num != -1) {
            db = mongoClient.getDB("my_database");
            coll = db.getCollection("TB_titleID");
            w = new WriteConcern(1, 0);// ? ,   2000 // ? 2 ??  ? ?
            mongoClient.setWriteConcern(w);

            // string?  select
            query = new BasicDBObject();
            //
            query.put("ID", num);
            //query.put("to",to);
            cursor = coll.find(query);
            if (cursor.hasNext())// ?? 
            {
                System.out.println("num : " + num);
                DBObject mapObj = cursor.next();
                returntour.myURL = mapObj.get("url").toString();
                returntour.myLocation = Integer.parseInt(mapObj.get("num").toString());
                cursor.close();
            } else {
                returntour.myURL = null;
                returntour.myLocation = 0;
            }
        }
        mongoClient.close();
    } catch (Exception e) {
        System.err.println("findwithDB Exception");
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
    return returntour;
}

From source file:twittermongodbapp.CollectTweets.java

static public void collectTweets(DB db, ConfigurationBuilder cf1, twitter4j.Twitter twitter) {

    TwitterStream twitterStream = new TwitterStreamFactory(cf1.build()).getInstance();

    DBCollection collection = db.getCollection("collection");
    DBCollection collection2 = db.getCollection("collection2");
    BasicDBObject document0 = new BasicDBObject();
    collection.remove(document0);/*  w ww.  j ava2  s .  c  o m*/
    collection2.remove(document0);
    StatusListener listener = new StatusListener() {

        @Override
        public void onStatus(Status status) {
            if (collection2.getCount() == 15000)
                System.exit(0);
            String json = DataObjectFactory.getRawJSON(status);
            DBObject doc = (DBObject) JSON.parse(json);
            try {
                collection2.insert(doc);
            } catch (Exception e) {
                System.out.println("MongoDB Connection Error : " + e.getMessage());
            }

            System.out.println("Collected tweets :" + collection2.getCount());

        }

        @Override
        public void onException(Exception ex) {
            ex.printStackTrace();

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onScrubGeo(long arg0, long arg1) {

        }

        @Override
        public void onStallWarning(StallWarning arg0) {
            // TODO Auto-generated method stub
            System.out.println(arg0);
        }

        @Override
        public void onTrackLimitationNotice(int arg0) {
            // TODO Auto-generated method stub
            System.out.println(arg0);
        }
    };
    getTopTrends(twitter, twitterStream, listener);
}