Example usage for com.mongodb DBCursor count

List of usage examples for com.mongodb DBCursor count

Introduction

In this page you can find the example usage for com.mongodb DBCursor count.

Prototype

public int count() 

Source Link

Document

Counts the number of objects matching the query.

Usage

From source file:japura.Tribes.Tribes.java

License:BSD License

public static String[] getTribeNames() {
    if (tribeNameCache == null) {
        log("rebuilding tribe name cache");
        DBCursor cursor = Tribes.getTribes();
        Tribe group;/*  w ww  .j  a v  a2  s.  c o m*/
        tribeNameCache = new String[cursor.count()];
        int index = 0;
        while (cursor.hasNext()) {
            tribeNameCache[index++] = (String) cursor.next().get("name");
        }
    }

    return tribeNameCache;
}

From source file:javaapplication1.InsertUser.java

public static void main(String[] args) {

    MongoClient mongo = new MongoClient("localhost", 27017);

    DB db = mongo.getDB("PaperTree");

    DBCollection user = db.getCollection("User");
    Document d = new Document();
    d.put("Name", new Document().append("First Name", "Akshay").append("Last Name", "Chandila"));
    d.put("Email", "akki@gmail.com");
    d.put("Interests", "Computer Science");
    d.put("Password", "shaolinp");
    d.put("Security Question", "a?");
    d.put("Security Answer", "b");
    DBObject ob = new BasicDBObject(d);
    user.insert(ob);//from  w ww.j  a v  a2s. co m

    DBObject ob1 = new BasicDBObject(new Document("Password", "shaolinp"));
    DBObject ob2 = new BasicDBObject(new Document("$set", new Document("Security Answer", "Akshay1234")));
    user.update(ob1, ob2);
    String tm = "shaolghjmkl;inp";
    DBObject ob3 = new BasicDBObject(new Document("Password", tm));
    DBCursor c2 = user.find(ob3);
    System.out.println(c2.count());
}

From source file:javasensei.db.managments.RankingManager.java

public FastByIDMap buildDataModel(DBCollection rankings, String fieldNameUserId, String fieldNameItemId,
        String fieldNameValue) {//from w w  w.  j  av  a2s.c  om
    //Obtenemos todos los ranking actuales y los almacenamos en el archivo csv
    DBCursor cursor = rankings.find();
    FastByIDMap<PreferenceArray> userData = new FastByIDMap<>();

    if (cursor.count() > 0) {

        List<Preference> preferences = new ArrayList<>();
        Long idLastUser = null;

        while (cursor.hasNext()) {
            DBObject object = cursor.next();
            Long idItem = new Double(object.get(fieldNameItemId).toString()).longValue();
            Long idCurrentUser = new Double(object.get(fieldNameUserId).toString()).longValue();
            Float value = new Float(object.get(fieldNameValue).toString());

            if (idLastUser == null || !idCurrentUser.equals(idLastUser)) {
                if (preferences.size() > 0) {
                    userData.put(idLastUser, new GenericUserPreferenceArray(preferences));
                    preferences.clear();
                }
                idLastUser = idCurrentUser;
            }

            preferences.add(new GenericPreference(idLastUser, idItem, value));

            if (!cursor.hasNext()) {
                userData.put(idLastUser, new GenericUserPreferenceArray(preferences));
            }
        }

        System.out.println(userData);
    }

    return userData;
}

From source file:Modules.Client.Model.DAO.DAO_Mongo_client.java

public static void load_Clients() {
    DBCollection table = Singleton_app.collection;
    DBCursor cursor = null;
    Client_class client = new Client_class();

    try {// w w  w.  java2 s . c  o m
        cursor = table.find();
        if (cursor.count() != 0) {
            while (cursor.hasNext()) {
                BasicDBObject document = (BasicDBObject) cursor.next();
                Singleton_client.cli.add(client.Client_from_DB(document));
            }
        } else {
            System.out.println("NO DATA");
        }

    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

}

From source file:Modules.Client.Model.DAO.DAO_Mongo_client.java

public static Client_class load_client_dni(String dni) {
    DBCollection table = Singleton_app.collection;
    DBCursor cursor = null;
    Client_class c = new Client_class();
    //        System.out.println("Modules.Client.Model.DAO.DAO_Mongo_client.load_client_dni()");
    try {/*from ww w. j av a  2 s  .  com*/
        BasicDBObject query = new BasicDBObject();
        query.put("dni", dni);

        cursor = table.find(query);
        if (cursor.count() != 0) {
            while (cursor.hasNext()) {
                BasicDBObject document = (BasicDBObject) cursor.next();
                c = c.Client_from_DB(document);

            }
        } else {
            //                System.out.println("NO DATA");
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    return c;

}

From source file:modules.Sign_In.model.DAO_SignIn.DAO_SignIn.java

/**
 * funcion para buscar un cliente por DNI en MongoDB
 *//*from   w w w .  j  ava2 s .  c o m*/
public static void searchClientDAO() {
    DBCursor cursor = null;
    singleton.userclient.clear();
    client c = new client();
    try {

        BasicDBObject searchClient = new BasicDBObject();
        c = new client(Sign_In.dniField.getText());
        searchClient.append("dni", c.getDni());
        cursor = singletonMongo.collection.find(searchClient);
        if (cursor.count() != 0) {
            while (cursor.hasNext()) {
                BasicDBObject document = (BasicDBObject) cursor.next();
                singleton.client = c.Mongo_to_client(document);
            }
        } else {
            System.out.println("NOT DATA");
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:modules.users.client.model.DAO.DAO_Mongo.java

/**
 * lista los clientes que hay guardados en MongoDB
 *///w  w w.  ja  v  a2s . c om
public static void viewTableClient() {
    DBCursor cursor = null;
    singleton.userclient.clear();
    client c = new client();
    try {
        cursor = singletonMongo.collection.find();
        if (cursor.count() != 0) {
            while (cursor.hasNext()) {
                BasicDBObject document = (BasicDBObject) cursor.next();
                singleton.client = c.Mongo_to_client(document);
                singleton.userclient.add(singleton.client);

            }
        } else {
            System.out.println("NOT DATA");
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public HashMap<String, String> getInitialStats() {

    HashMap<String, String> stats = new HashMap<String, String>();
    com.mongodb.DB db = null;//from   w  w w  . ja va 2 s .  c o m
    try {
        db = mongo.getDB(database);
        db.requestStart();
        // get the number of users
        DBCollection collection = db.getCollection("users");
        DBCursor users = collection.find();
        int usercnt = users.count();
        users.close();
        stats.put("usercount", Integer.toString(usercnt));

        // find user offset
        DBObject m = new BasicDBObject().append("_id", 1);
        DBCursor minUser = collection.find(m).limit(1);
        int offset = 0;
        if (minUser.hasNext())
            offset = (Integer) minUser.next().toMap().get("_id");
        minUser.close();
        // get the number of friends per user
        DBObject q = new BasicDBObject().append("_id", offset);
        DBObject queryResult = null;
        queryResult = collection.findOne(q);
        String x = queryResult.get("ConfFriends").toString();
        int frndCount = 0;
        if (x.equals("") || (!x.equals("") && (x.substring(2, x.length() - 1)).equals("")))
            frndCount = 0;
        else {
            x = x.substring(2, x.length() - 1);
            frndCount = x.split(",").length;
        }
        stats.put("avgfriendsperuser", Integer.toString(frndCount));

        x = queryResult.get("PendFriends").toString();
        int pendCount = 0;
        if (x.equals("") || (!x.equals("") && (x.substring(2, x.length() - 1)).equals("")))
            pendCount = 0;
        else {
            x = x.substring(2, x.length() - 1);
            pendCount = x.split(",").length;
        }
        stats.put("avgpendingperuser", Integer.toString(pendCount));

        // find number of resources for the user
        DBCollection resCollection = db.getCollection("resources");
        DBObject res = new BasicDBObject().append("creatorid", Integer.toString(offset));
        DBCursor resQueryResult = null;
        resQueryResult = resCollection.find(res);
        int resCount = resQueryResult.count();
        resQueryResult.close();
        stats.put("resourcesperuser", Integer.toString(resCount));
    } catch (Exception e) {
        e.printStackTrace(System.out);
    } finally {
        if (db != null)
            db.requestDone();
    }
    return stats;
}

From source file:mongodb.MongoDBOperations.java

License:Apache License

public void geoFindAndUpdate(DBCollection coll, BasicDBObject queryObject) {
    int query_count = 0;
    int processed_count = 0;
    int updated_count = 0;
    DBCursor cursor = coll.find(queryObject);
    try {/*  ww  w.  j  av  a 2 s  .  co m*/
        query_count = cursor.count();
        while (cursor.hasNext()) {
            BasicDBObject myDoc = (BasicDBObject) cursor.next();
            Object userLocationObj = myDoc.get("user_location");
            String location = String.valueOf(userLocationObj);

            ObjectId ID = (ObjectId) myDoc.get("_id");
            System.out.println("Queried Document: " + myDoc);

            GeoCodingClient gcc = new GeoCodingClient(this.conf);
            Thread.sleep(200);
            DBObject update = gcc.getGeoCode(location);
            //System.out.println(update);

            if (update == null) {
                System.out.print("No updates (update==null)");
                break;
            } else {
                Set<String> keyset = update.keySet();
                if (keyset == null) {
                    System.out.print("No updates (keyset==null)");
                } else if (keyset.contains("geocode")) {
                    updated_count++;
                    coll.update(new BasicDBObject().append("_id", ID),
                            myDoc.append("geocode", update.get("geocode")));
                    System.out.println(
                            "Updated Doc:\n" + coll.find(new BasicDBObject().append("_id", ID)).next());
                    System.out.println("In this run: (" + processed_count + " records processed, "
                            + updated_count + " records updated.)");
                } else if (keyset.contains("status")
                        && update.get("status").toString().contains("OVER_QUERY_LIMIT")) {
                    break;
                }
            }
            processed_count++;
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } finally {
        cursor.close();
        System.out.println("In this run:");
        System.out.println("Total:" + query_count + " record(s) found.");
        System.out.println("Total:" + processed_count + " record(s) processed.");
        System.out.println("Total:" + updated_count + " record(s) updated.");
    }

}

From source file:mongodb.question2.java

public static void main(String[] args) throws UnknownHostException, MongoException {

    Mongo mongoclient = new Mongo();

    DB db = mongoclient.getDB("db");

    DBCollection Collection = db.getCollection("tags_import");

    //Need to enter the userid
    System.out.println("Enter the User Id here");
    Scanner userid = new Scanner(System.in);
    String UserId = userid.next();

    BasicDBObject user = new BasicDBObject();
    user.put("UserID", UserId);

    DBCursor usercursor = Collection.find();
    usercursor = Collection.find(user);

    while (usercursor.hasNext()) {
        DBObject object = usercursor.next();
        String MovieID = (String) object.get("MovieID");

        System.out.println("MovieID is " + MovieID);

        //for each Movie Id find the target id
        BasicDBObject targetid = new BasicDBObject();
        targetid.put("MovieID", MovieID);

        DBCursor moviecursor = Collection.find();
        moviecursor = Collection.find(targetid);

        int count = moviecursor.count();
        System.out.println("This movie has been rated " + count + " users");
        System.out.println(count);

        while (moviecursor.hasNext()) {
            DBObject object2 = moviecursor.next();
            String folluserID = (String) object2.get("UserID");
            System.out.println("The following  Users are familiar to the given user  " + folluserID);
        }/*from   ww w. ja  v a 2 s.  c  o  m*/
        System.out.println();
    }

}