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:me.philnate.textmanager.updates.Update12_12.java

License:Open Source License

private void postCheckNameSplit() {
    // check that no docs with customerName are remaining
    DBCollection customer = ds.getCollection(Customer.class);
    checkArgument(0 == customer.find(QueryBuilder.start("contactName").exists(true).get()).count(),
            "Found customer object with contactName. Should not happen!");
    // check that all have at least a lastName, as customerName was required
    // before/*  www . j  ava 2  s . c  om*/
    checkArgument(customer.getCount() == customer
            .find(QueryBuilder.start("contactName").exists(false).and("lastName").exists(true).get()).count(),
            "Found customer without lastName");
}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public void reconstructSchema() {
    com.mongodb.DB db = null;/*  w ww  .  j  a  v a2 s  . c  om*/
    try {
        db = mongo.getDB(database);
        db.requestStart();
        // getting the number of users
        DBCollection collection = db.getCollection("users");
        int numUsers = (int) collection.getCount();
        // for every user set their conf Friends and pend Friends to null
        for (int i = 0; i < numUsers; i++) {
            DBObject r = new BasicDBObject().append("_id", i);
            DBObject queryResult = collection.findOne(r);
            BasicDBObject updateCommand = new BasicDBObject();
            updateCommand.put("$set", new BasicDBObject("ConfFriends", new ArrayList<Integer>()));
            WriteResult res = collection.update(r, updateCommand, false, false, writeConcern);
            updateCommand = new BasicDBObject();
            updateCommand.put("$set", new BasicDBObject("PendFriends", new ArrayList<Integer>()));
            res = collection.update(r, updateCommand, false, false, writeConcern);
        }
        if (manipulationArray) {
            collection = db.getCollection("resources");
            int numResources = (int) collection.getCount();
            // for every user set their conf Friends and pend Friends to null
            for (int i = 0; i < numUsers; i++) {
                DBObject r = new BasicDBObject().append("_id", i);
                DBObject queryResult = collection.findOne(r);
                BasicDBObject updateCommand = new BasicDBObject();
                updateCommand.put("$set", new BasicDBObject("Manipulations", new ArrayList<Integer>()));
                WriteResult res = collection.update(r, updateCommand, false, false, writeConcern);
            }
        } else {
            collection = db.getCollection("manipulation");
            //TODO: test this
            if (Boolean.parseBoolean(
                    props.getProperty(MONGODB_SHARDING_PROPERTY, MONGODB_SHARDING_PROPERTY_DEFAULT)) == true)
                collection.drop(); //this doesnt work with shards
            else {
                DBCursor DBCur = collection.find();
                while (DBCur.hasNext())
                    collection.remove(DBCur.next());
            }

        }

        db.requestDone();
    } catch (Exception ex) {
        db.requestDone();
        ex.printStackTrace();
    }
}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public boolean dataAvailable() {
    com.mongodb.DB db = null;//w w w. j  a  va2 s  .c o m
    Properties props = getProperties();
    try {
        db = mongo.getDB(database);

        //getting the number of users
        db.requestStart();
        DBCollection collection = db.getCollection("users");
        int numUsers = (int) collection.getCount();
        if (numUsers != Integer
                .parseInt(props.getProperty(Client.USER_COUNT_PROPERTY, Client.USER_COUNT_PROPERTY_DEFAULT))) {
            db.requestDone();
            return false;
        }
        db.requestDone();

        //getting the number of resources
        //getting the number of users
        db.requestStart();
        collection = db.getCollection("resources");
        int numResources = (int) collection.getCount();
        if (numResources != (Integer
                .parseInt(props.getProperty(Client.USER_COUNT_PROPERTY, Client.USER_COUNT_PROPERTY_DEFAULT))
                * Integer.parseInt(props.getProperty(Client.RESOURCE_COUNT_PROPERTY,
                        Client.RESOURCE_COUNT_PROPERTY_DEFAULT)))) {
            db.requestDone();
            return false;
        }
        db.requestDone();
    } catch (Exception ex) {
        db.requestDone();
        ex.printStackTrace();
        return false;
    }
    return true;
}

From source file:MongoDb.MongoDBCollection.java

public static void main(String args[]) throws UnknownHostException, JSONException {
    long startTime = System.nanoTime();

    //Init//www.  j a  v a2  s  .c om
    MongoClient mongoClient = new MongoClient(MongoDb.Config.HOST, MongoDb.Config.defaultPort);
    DB db = mongoClient.getDB(MongoDb.Config.Schema);
    String colletioName = "websosanh";

    DBCollection collections = db.getCollection(colletioName);
    //MongoDBController mongDbController = new MongoDBController(mongoClient,db);
    //if(mongDbController.addACollection("")){
    for (int i = 1; i < 2; i++) {
        JSONObject json = new JSONObject();
        json.put("status", "ok");
        MongoDBController.addDocumentFromJsonToJsonObject(json, collections);
        //System.out.println(collections.getCount());
    }
    long endTime = System.nanoTime();
    long duration = (endTime - startTime);
    System.out.println(collections.getCount());
    System.out.println("Time Total excute is " + duration);

    //}

}

From source file:net.autosauler.ballance.server.model.Currency.java

License:Apache License

/**
 * Creates the default records./*from   w w  w  .  ja  v a 2 s .  c o m*/
 * 
 * @param db
 *            the db
 */
public static void createDefaultRecords(DB db) {

    if (db != null) {
        DBCollection coll = db.getCollection(CURRENCYTABLE);
        if (coll.getCount() < 1) {
            if (formatter == null) {
                formatter = new SimpleDateFormat(CBRDATEFORMAT);
            }
            String day = formatter.format(new Date());
            receiveCBR(day, db);

            BasicDBObject i = new BasicDBObject();
            i.put("date", 1);
            i.put("mnemo", 1);

            coll.createIndex(i);

            i = new BasicDBObject();
            i.put("timestamp", 1);
            i.put("mnemo", 1);

            coll.createIndex(i);

        }
    }
}

From source file:net.autosauler.ballance.server.model.GlobalSettings.java

License:Apache License

/**
 * Creates the default records./* w  w w  .j a  v a2s.  com*/
 * 
 * @param db
 *            the db
 */
public static void createDefaultRecords(DB db) {

    if (db != null) {
        DBCollection coll = db.getCollection(SETTINGSTABLE);
        if (coll.getCount() < 1) {

            BasicDBObject rec = new BasicDBObject();
            rec.put("name", "default.record");
            rec.put("val", "default.value");
            coll.insert(rec);

            BasicDBObject i = new BasicDBObject();
            i.put("domain", 1);
            i.put("name", 1);
            coll.createIndex(i);

        }
    }
}

From source file:net.autosauler.ballance.server.model.UserList.java

License:Apache License

/**
 * Creates the default records if no users in database.
 * //  w  ww. java 2s .c o  m
 * @param db
 *            the db
 */
public static void createDefaultRecords(DB db) {

    if (db != null) {
        DBCollection coll = db.getCollection(collectionname);
        if (coll.getCount() < 1) {
            UserRole defaultroles = new UserRole();
            defaultroles.setAdmin();

            User user = new User();
            user.setPassword("admin");
            user.setLogin("admin");
            user.setDomain("127.0.0.1");
            user.setUsername("Admin The Great");
            user.setUserrole(defaultroles);
            user.addNewUser();

            BasicDBObject i = new BasicDBObject();
            i.put("login", 1);
            i.put("domain", 1);

            coll.createIndex(i);

            i.put("istrash", 1);
            coll.createIndex(i);
        }
    }
}

From source file:no.nlf.avvik.melwinSOAPconnection.MongoOperations.java

/**
 * // www.j  a  v a  2 s .  co  m
 * @return
 */
private boolean checkIfJumpersCollectionIsEmpty(DBCollection dbCollection) {
    if (dbCollection.getCount() == 0) {
        return true;
    }
    return false;
}

From source file:org.apache.isis.objectstore.nosql.db.mongo.MongoDb.java

License:Apache License

@Override
public boolean hasInstances(final ObjectSpecId objectSpecId) {
    final DBCollection instances = db.getCollection(objectSpecId.asString());
    return instances.getCount() > 0;
}

From source file:parlare.application.server.model.Database.java

private String doClientMongo() {

    String print = "";

    System.out.println("User:" + user + " Source:" + source + " Password:" + password);

    try {// w  ww . ja  va2 s  .  co m

        // connect to the local database server
        MongoClient mongoClient = new MongoClient(new ServerAddress(server),
                Arrays.asList(MongoCredential.createMongoCRCredential(user, source, password.toCharArray())),
                new MongoClientOptions.Builder().build());

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

        // Authenticate - optional
        // boolean auth = db.authenticate("foo", "bar");

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

            System.out.println(s);
        }

        // get a collection object to work with
        DBCollection testCollection = db.getCollection("testCollection");

        // drop all the data in it
        testCollection.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));

        testCollection.insert(doc);

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

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

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

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

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

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

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

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

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

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

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

        // See if the last operation had an error
        System.out.println("Last error : " + db.getLastError());

        // see if any previous operation had an error
        System.out.println("Previous error : " + db.getPreviousError());

        // force an error
        db.forceError();

        // See if the last operation had an error
        System.out.println("Last error : " + db.getLastError());

        db.resetError();

        // release resources
        mongoClient.close();

    } catch (UnknownHostException ex) {
        Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
    }

    return print;

}