Example usage for com.mongodb DBCollection count

List of usage examples for com.mongodb DBCollection count

Introduction

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

Prototype

public long count(@Nullable final DBObject query) 

Source Link

Document

Same as #getCount(DBObject)

Usage

From source file:com.foodtruckdata.mongodb.UsersInput.java

@Override
public boolean TruckExists(String title, String email) {
    BasicDBObject filter = new BasicDBObject();
    BasicDBObject clause1 = new BasicDBObject("title", title);
    BasicDBObject clause2 = new BasicDBObject("email", email);
    filter.put("$or", new BasicDBObject[] { clause1, clause2 });
    DBCollection coll = mongoDB.getCollection("Trucks");
    return coll.count(filter) > 0;
}

From source file:com.glaf.wechat.mongodb.service.impl.WxMongoDBLogServiceImpl.java

License:Apache License

public int getWxLogCountByQueryCriteria(WxLogQuery query) {
    DB db = mongoTemplate.getDb();/*ww w  . j  a v a 2 s  .  c  o m*/
    String tableName = "wx_log" + query.getSuffix();
    DBCollection coll = db.getCollection(tableName);
    if (coll != null) {
        BasicDBObject q = new BasicDBObject();
        this.fillQueryCondition(q, query);
        int count = (int) coll.count(q);
        logger.debug("count=" + count);
        return count;
    }
    return 0;
}

From source file:com.impetus.client.mongodb.MongoDBClient.java

License:Apache License

/**
 * Gets the DB cursor instance./*from  w w w. j a  v  a  2  s . c  o  m*/
 * 
 * @param mongoQuery
 *            the mongo query
 * @param orderBy
 *            the order by
 * @param maxResult
 *            the max result
 * @param firstResult
 *            the first result
 * @param keys
 *            the keys
 * @param documentName
 *            the document name
 * @param isCountQuery
 *            the is count query
 * @return the DB cursor instance
 */
public Object getDBCursorInstance(BasicDBObject mongoQuery, BasicDBObject orderBy, int maxResult,
        int firstResult, BasicDBObject keys, String documentName, boolean isCountQuery) {
    DBCollection dbCollection = mongoDb.getCollection(documentName);
    DBCursor cursor = null;
    if (isCountQuery)
        return dbCollection.count(mongoQuery);
    else
        cursor = orderBy != null
                ? dbCollection.find(mongoQuery, keys).sort(orderBy).limit(maxResult).skip(firstResult)
                : dbCollection.find(mongoQuery, keys).limit(maxResult).skip(firstResult);
    return cursor;
}

From source file:com.petpet.c3po.dao.mongo.MongoPersistenceLayer.java

License:Apache License

/**
 * {@inheritDoc}/*from  ww w. ja  v a 2s .c  om*/
 */
@Override
public <T extends Model> long count(Class<T> clazz, Filter filter) {

    DBObject query = this.getCachedFilter(filter);
    DBCollection dbCollection = this.getCollection(clazz);
    return dbCollection.count(query);

}

From source file:com.petpet.c3po.dao.mongo.MongoPersistenceLayer.java

License:Apache License

public <T extends Model> long count(Class<T> clazz, DBObject query) {

    DBCollection dbCollection = this.getCollection(clazz);
    return dbCollection.count(query);

}

From source file:com.servlet.UserDublicate.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//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 {
    String email = request.getParameter("searchId");

    DBcon dbcon = new DBcon();
    dbcon.getDbCon();
    DBCollection coll = dbcon.getData("employee");
    PrintWriter out = response.getWriter();
    BasicDBObject basic = new BasicDBObject();
    basic.put("email", email);

    if (coll.count(basic) == 0) {
        out.print("Username is valid");

    } else {
        out.print("Username is invalid");
    }

}

From source file:com.softinstigate.restheart.db.CollectionDAO.java

License:Open Source License

/**
 * Checks if the given collection is empty. Note that RESTHeart creates a
 * reserved properties document in every collection (with _id
 * '_properties'). This method returns true even if the collection contains
 * such document.//from   ww  w. ja v  a2s.c  o m
 *
 * @param coll the mongodb DBCollection object
 * @return true if the commection is empty
 */
public static boolean isCollectionEmpty(DBCollection coll) {
    return coll.count(DOCUMENTS_QUERY) == 0;
}

From source file:com.softinstigate.restheart.db.CollectionDAO.java

License:Open Source License

/**
 * Returns the number of documents in the given collection (taking into
 * account the filters in case)./*  www .j  a v  a 2s.c  o  m*/
 *
 * @param coll the mongodb DBCollection object.
 * @param filters the filters to apply. it is a Deque collection of mongodb
 * query conditions.
 * @return the number of documents in the given collection (taking into
 * account the filters in case)
 */
public static long getCollectionSize(DBCollection coll, Deque<String> filters) {
    final BasicDBObject query = new BasicDBObject(DOCUMENTS_QUERY);

    if (filters != null) {
        try {
            filters.stream().forEach(f -> {
                query.putAll((BSONObject) JSON.parse(f)); // this can throw JSONParseException for invalid filter parameters
            });
        } catch (JSONParseException jpe) {
            logger.warn("****** error parsing filter expression {}", filters, jpe);
        }
    }

    return coll.count(query);
}

From source file:com.softinstigate.restheart.db.CollectionDAO.java

License:Open Source License

/**
 * Upsert the collection properties.//from w  w w . ja va 2  s .  c  o  m
 *
 * @param dbName the database name of the collection
 * @param collName the collection name
 * @param content the new collection properties
 * @param etag the entity tag. must match to allow actual write (otherwise
 * http error code is returned)
 * @param updating true if updating existing document
 * @param patching true if use patch semantic (update only specified fields)
 * @return the HttpStatus code to set in the http response
 */
public static int upsertCollection(String dbName, String collName, DBObject content, ObjectId etag,
        boolean updating, boolean patching) {
    DB db = DBDAO.getDB(dbName);

    DBCollection coll = db.getCollection(collName);

    if (patching && !updating) {
        return HttpStatus.SC_NOT_FOUND;
    }

    if (updating) {
        if (etag == null) {
            return HttpStatus.SC_CONFLICT;
        }

        BasicDBObject idAndEtagQuery = new BasicDBObject("_id", "_properties");
        idAndEtagQuery.append("_etag", etag);

        if (coll.count(idAndEtagQuery) < 1) {
            return HttpStatus.SC_PRECONDITION_FAILED;
        }
    }

    ObjectId timestamp = new ObjectId();
    Instant now = Instant.ofEpochSecond(timestamp.getTimestamp());

    if (content == null) {
        content = new BasicDBObject();
    }

    content.removeField("_id"); // make sure we don't change this field

    if (updating) {
        content.removeField("_crated_on"); // don't allow to update this field
        content.put("_etag", timestamp);
    } else {
        content.put("_id", "_properties");
        content.put("_created_on", now.toString());
        content.put("_etag", timestamp);
    }

    if (patching) {
        coll.update(PROPS_QUERY, new BasicDBObject("$set", content), true, false);
        return HttpStatus.SC_OK;
    } else {
        // we use findAndModify to get the @created_on field value from the existing properties document
        // we need to put this field back using a second update 
        // it is not possible in a single update even using $setOnInsert update operator
        // in this case we need to provide the other data using $set operator and this makes it a partial update (patch semantic) 

        DBObject old = coll.findAndModify(PROPS_QUERY, fieldsToReturn, null, false, content, false, true);

        if (old != null) {
            Object oldTimestamp = old.get("_created_on");

            if (oldTimestamp == null) {
                oldTimestamp = now.toString();
                logger.warn("properties of collection {} had no @created_on field. set to now",
                        coll.getFullName());
            }

            // need to readd the @created_on field 
            BasicDBObject createdContet = new BasicDBObject("_created_on", "" + oldTimestamp);
            createdContet.markAsPartialObject();
            coll.update(PROPS_QUERY, new BasicDBObject("$set", createdContet), true, false);

            return HttpStatus.SC_OK;
        } else {
            // need to readd the @created_on field 
            BasicDBObject createdContet = new BasicDBObject("_created_on", now.toString());
            createdContet.markAsPartialObject();
            coll.update(PROPS_QUERY, new BasicDBObject("$set", createdContet), true, false);

            initDefaultIndexes(coll);

            return HttpStatus.SC_CREATED;
        }
    }
}

From source file:com.softinstigate.restheart.db.DBDAO.java

License:Open Source License

/**
 *
 * @param dbName/*from   w w  w.j  a v a  2 s .c  o m*/
 * @param content
 * @param etag
 * @param patching
 * @return
 */
public static int upsertDB(String dbName, DBObject content, ObjectId etag, boolean patching) {
    DB db = client.getDB(dbName);

    boolean existing = db.getCollectionNames().size() > 0;

    if (patching && !existing) {
        return HttpStatus.SC_NOT_FOUND;
    }

    DBCollection coll = db.getCollection("_properties");

    // check the etag
    if (db.collectionExists("_properties")) {
        if (etag == null) {
            return HttpStatus.SC_CONFLICT;
        }

        BasicDBObject idAndEtagQuery = new BasicDBObject("_id", "_properties");
        idAndEtagQuery.append("_etag", etag);

        if (coll.count(idAndEtagQuery) < 1) {
            return HttpStatus.SC_PRECONDITION_FAILED;
        }
    }

    // apply new values
    ObjectId timestamp = new ObjectId();
    Instant now = Instant.ofEpochSecond(timestamp.getTimestamp());

    if (content == null) {
        content = new BasicDBObject();
    }

    content.put("_etag", timestamp);
    content.removeField("_created_on"); // make sure we don't change this field
    content.removeField("_id"); // make sure we don't change this field

    if (patching) {
        coll.update(METADATA_QUERY, new BasicDBObject("$set", content), true, false);

        return HttpStatus.SC_OK;
    } else {
        // we use findAndModify to get the @created_on field value from the existing document
        // we need to put this field back using a second update 
        // it is not possible in a single update even using $setOnInsert update operator
        // in this case we need to provide the other data using $set operator and this makes it a partial update (patch semantic) 
        DBObject old = coll.findAndModify(METADATA_QUERY, fieldsToReturn, null, false, content, false, true);

        if (old != null) {
            Object oldTimestamp = old.get("_created_on");

            if (oldTimestamp == null) {
                oldTimestamp = now.toString();
                logger.warn("properties of collection {} had no @created_on field. set to now",
                        coll.getFullName());
            }

            // need to readd the @created_on field 
            BasicDBObject createdContet = new BasicDBObject("_created_on", "" + oldTimestamp);
            createdContet.markAsPartialObject();
            coll.update(METADATA_QUERY, new BasicDBObject("$set", createdContet), true, false);

            return HttpStatus.SC_OK;
        } else {
            // need to readd the @created_on field 
            BasicDBObject createdContet = new BasicDBObject("_created_on", now.toString());
            createdContet.markAsPartialObject();
            coll.update(METADATA_QUERY, new BasicDBObject("$set", createdContet), true, false);

            return HttpStatus.SC_CREATED;
        }
    }
}