Java - MongoDB Group Count

摘要:Java - MongoDB Group Count

 
    public int getDataCount(String condition_key)
    {
        int mongo_total = 0 ;
        boolean flag = false;
        Mongo mongo = null;
        DB db = null;
 
        try {
            mongo = this.dao.getMongo();
            db = this.dao.getDB(mongo);
            DBCollection collection = db.getCollection(this.collection_name);
            // create our pipeline operations, first with the $match
            DBObject match = new BasicDBObject("$match", new BasicDBObject("condition_key", condition_key) );
 
            // build the $projection operation
            DBObject fields = new BasicDBObject("project_key", 1);
            fields.put("count_key", 1);
            DBObject project = new BasicDBObject("$project", fields );
 
            // Now the $group operation
            DBObject groupFields = new BasicDBObject( "_id", "count_key");
            groupFields.put("count", new BasicDBObject( "$sum", 1));
            DBObject group = new BasicDBObject("$group", groupFields);
 
            // run aggregation
            AggregationOutput output = collection.aggregate( match, project, group );
            for(DBObject obj:output.results())
            {
                 BasicDBObject obj2 = (BasicDBObject)obj;
                 mongo_total = obj2.getInt("count");
            }
 
        } catch (Exception ex) {
            flag = false;
            log.error(OtherTool.getTool().getErrorStackMessage(ex));
        }
        finally {
            this.dao.safeClose(mongo,db);
        }
        return mongo_total;
    }
 
參考