Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.bitbucket.davidm24.mongodb.aggregate;
  
Utility for creating DBObject $group body clauses.

Author(s):
David M. Carr
See also:
Aggregation Framework in MongoDB Manual
 
 public class GroupBuilder {
     public GroupBuilder() {
          = new BasicDBObject();
     }

    
Returns a new GroupBuilder
 
     public static GroupBuilder start() {
         return new GroupBuilder();
     }
 
     public static GroupBuilder start(String targetField) {
         return start().push(targetField);
     }
 
     private void addOperand(String opObject value) {
         if ( == null) {
             throw new GroupBuilderException("No target field for operand");
         }
         if (op == null) {
             .put(value);
         } else {
             .put(new BasicDBObject(opvalue));
         }
     }
 
     public GroupBuilder put(String key) {
          = key;
         if (.get(key) == null) {
             .put(new NullObject());
         }
         return this;
     }
 
     public GroupBuilder to(Object object) {
         addOperand(nullobject);
         return this;
     }
 
     public GroupBuilder sum(int num) {
         addOperand(.num);
         return this;
     }
 
     public GroupBuilder sum(String targetField) {
         addOperand(.targetField);
         return this;
     }
 
     public GroupBuilder addToSet(String targetField) {
         addOperand(.targetField);
         return this;
     }
 
     public GroupBuilder first(String targetField) {
         addOperand(.targetField);
         return this;
     }
 
     public GroupBuilder last(String targetField) {
         addOperand(.targetField);
         return this;
     }
 
     public GroupBuilder max(String targetField) {
         addOperand(.targetField);
         return this;
     }
 
     public GroupBuilder min(String targetField) {
         addOperand(.targetField);
         return this;
     }
 
     public GroupBuilder avg(String targetField) {
         addOperand(.targetField);
         return this;
     }
 
     public GroupBuilder push(String targetField) {
         addOperand(.targetField);
         return this;
     }

    
Creates a DBObject to be passed to a $group operator

Returns:
Returns a DBObject instance
Throws:
java.lang.RuntimeException if a key does not have a matching operand
    public DBObject get() {
        for(String key : .keySet()) {
            if(.get(keyinstanceof NullObject) {
                throw new GroupBuilderException("No operand for key: " + key);
            }
        }
        return ;
    }
    @SuppressWarnings("serial")
	static class GroupBuilderException extends RuntimeException {
        GroupBuilderException(String message) {
            super(message);
        }
	}
    private static class NullObject {}
    private DBObject _body;
    private String _currentKey;
New to GrepCode? Check out our FAQ X