Example usage for com.mongodb BasicDBObject append

List of usage examples for com.mongodb BasicDBObject append

Introduction

In this page you can find the example usage for com.mongodb BasicDBObject append.

Prototype

@Override
public BasicDBObject append(final String key, final Object val) 

Source Link

Document

Add a key/value pair to this object

Usage

From source file:com.logger.log.GameLog.java

/**
 * ?// w w w .j a  v a2s  .c o m
 *
 * @param type
 * @param userId
 * @param time
 * @param userName ??????/null
 * @param expands
 */
public static void saveUserActionLog(final LogType type, final int userId, final Date time,
        final String userName, final String... expands) {
    user_save_pools.execute(new Runnable() {
        @Override
        public void run() {
            BasicDBObject map = new BasicDBObject();
            map.append("userId", userId);
            mananger.append(type.name(), map);
        }
    });
}

From source file:com.logger.mongo.JvmMonitor.java

public void record() {
    String message = "memoryUsed=" + getMemoryUsed() + "k " + " cpuUsed=" + getCpu() + " threadCount="
            + getThreadCount();// ww  w  . j a  va  2 s. co  m
    BasicDBObject logEntry = new BasicDBObject();
    logEntry.append("message", message);
    logEntry.append("timestamp", System.currentTimeMillis());
    String collection = getIp() + "_" + getPid();
    connectionSource.getDB("memory_sysm").getCollection(collection).insert(logEntry);
    if (logToLocal) {
        System.out.println(String.format("%s %s", new Date(), message));
    }

}

From source file:com.maoyan.pf.webcollector.spider.AttendrateCrawler.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Executor executor = new Executor() {
        @Override/*from  w  w  w.  j  a v  a  2s  .c  om*/
        public void execute(CrawlDatum datum, CrawlDatums next) throws Exception {
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            // ?
            // DBCollection dbCollection = mongoClient.getDB("maoyan_crawler").getCollection("rankings_am"); 
            DB db = mongoClient.getDB("maoyan_crawler");
            // ?????
            Set<String> colls = db.getCollectionNames();
            for (String s : colls) {
                // Collection(?"")
                if (s.equals("attend_rate")) {
                    db.getCollection(s).drop();
                }
            }
            DBCollection dbCollection = db.getCollection("attend_rate");
            HtmlUnitDriver driver = new HtmlUnitDriver();
            driver.setJavascriptEnabled(false);
            driver.get(datum.getUrl());
            //                System.out.println(driver.getPageSource());
            WebElement element = driver.findElementByCssSelector("div#seat_table");
            List<WebElement> movie_name = element.findElements(By.className("c1 lineDot"));
            List<WebElement> boxoffice_rate = element.findElements(By.className("c2 red"));
            List<WebElement> visit_pershow = element.findElements(By.className("c3 gray"));
            WebElement cityarea = driver.findElementByCssSelector("span[class='today']");
            System.out.println(cityarea.getText());
            for (int i = 0; i < movie_name.size(); i++) {
                System.out.println(movie_name.get(i).getText());
                System.out.println(boxoffice_rate.get(i).getText());
                System.out.println(visit_pershow.get(i).getText());
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.append("title", cityarea.getText()).append("movie_name", movie_name.get(i).getText())
                        .append("boxoffice_rate", boxoffice_rate.get(i).getText())
                        .append("visit_pershow", visit_pershow.get(i).getText());
                dbCollection.insert(dbObject);
            }
            mongoClient.close();
        }
    };

    //DBDBManager
    DBManager manager = new BerkeleyDBManager("maoyan");
    //Crawler?DBManagerExecutor
    Crawler crawler = new Crawler(manager, executor);
    crawler.addSeed("http://pf.maoyan.com/attend/rate");
    crawler.start(1);
}

From source file:com.maoyan.pf.webcollector.spider.MoviestoreCrawler.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Executor executor = new Executor() {
        @Override// ww w  . j a v  a2 s.  co  m
        public void execute(CrawlDatum datum, CrawlDatums next) throws Exception {
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);
            Logger mongoLogger = Logger.getLogger("org.mongodb.driver");
            mongoLogger.setLevel(Level.ERROR);
            // ?
            // DBCollection dbCollection =
            // mongoClient.getDB("maoyan_crawler").getCollection("rankings_am");
            DB db = mongoClient.getDB("maoyan_crawler");
            // ?????
            DBCollection dbCollection = db.getCollection("movie_store");
            HtmlUnitDriver driver = new HtmlUnitDriver();
            driver.setJavascriptEnabled(false);
            driver.get(datum.getUrl());
            // System.out.println(driver.getPageSource());
            System.out.println(driver.findElement(By.xpath("//html/body/header/h1")).getText());
            // ProfilesIni pi = new ProfilesIni();
            // FirefoxProfile profile = pi.getProfile("default");
            // WebClient webClient = new
            // WebClient(BrowserVersion.FIREFOX_38);
            // driver.setJavascriptEnabled(false);
            // webClient.getOptions().setCssEnabled(true);
            // HtmlPage page = webClient.getPage(datum.getUrl());
            // System.out.println(page.asXml());
            // List<?> title =
            // page.getByXPath("//html/body/header/h1/text()");
            // List<?> score =
            // page.getByXPath("//html/body/section[1]/article[1]/aside/hgroup/article[1]/i/text()");
            // List<?> score_num =
            // page.getByXPath("//html/body/section[1]/article[1]/aside/hgroup/article[1]/span/text()");
            // List<?> want_num =
            // page.getByXPath("//html/body/section[1]/article[1]/aside/hgroup/article[2]/i/text()");
            // List<?> type =
            // page.getByXPath("//html/body/section[1]/article[1]/aside/p[1]/text()");
            // List<?> timing =
            // page.getByXPath("//html/body/section[1]/article[1]/aside/p[2]/text()");
            // List<?> system =
            // page.getByXPath("//html/body/section[1]/article[1]/aside/p[3]/text()");
            // List<?> onscreendate =
            // page.getByXPath("//html/body/section[1]/article[1]/aside/p[4]/text()");
            // List<?> total_rev =
            // page.getByXPath("//html/body/section[1]/article[2]/span[1]/text()");
            // List<?> firstweek_rev =
            // page.getByXPath("//html/body/section[1]/article[2]/span[2]/text()");
            // List<?> ahead_rev =
            // page.getByXPath("//html/body/section[1]/article[2]/span[3]/text()");
            // List<?> director =
            // page.getByXPath("//*[@id='infoContent']/article[1]/div/div[1]/div/div[2]/div[1]/div[2]/text()");
            // List<?> actor =
            // page.getByXPath("//*[@id='infoContent']/article[1]/div/div[1]/div/div[2]/div[2]/div[2]/text()");
            // List<?> production =
            // page.getByXPath("//*[@id='infoContent']/article[2]/div/div[1]/div/div[2]/text()");
            // List<?> distribution =
            // page.getByXPath("//*[@id='infoContent']/article[4]/div/div[1]/div/div[2]/text()");
            // List<?> technique =
            // page.getByXPath("//*[@id='infoContent']/article[5]/div/div[1]/div/div[2]/text()");
            // List<?> desc =
            // page.getByXPath("//*[@id='infoContent']/article[6]/div/div[2]/text()");
            // List<?> want_by_city =
            // page.getByXPath("//*[@id='wantCity']/ul/li[2]/b/text()");
            // List<?> want_val=
            // page.getByXPath("//*[@id='wantCity']/ul/li[3]/div/@style");
            // System.out.println(title);
            //// System.out.println(page.getByXPath("//span[@class='today']/em/text()"));
            //// System.out.println(page.getByXPath("//span[@class='today']/text()"));
            //// List<?> movie_name =
            // page.getByXPath("//div[@id='seat_table']//ul//li[@class='c1
            // lineDot']/text()");
            //// List<?> boxoffice_rate =
            // page.getByXPath("//div[@id='seat_table']//ul//li[@class='c2
            // red']/text()");
            //// List<?> visit_pershow =
            // page.getByXPath("//div[@id='seat_table']//ul//li[@class='c3
            // gray']/text()");
            //// for(int i = 0;i<movie_name.size();i++){
            //// System.out.println(movie_name.get(i));
            //// System.out.println(boxoffice_rate.get(i));
            //// System.out.println(visit_pershow.get(i));
            //// }
            // List<?> hbList = page.getByXPath("//div");
            // HtmlDivision hb = (HtmlDivision)hbList.get(0);
            // System.out.println(hb.toString());
            // System.out.println(ReturnString(driver,By.xpath("//*[@id='infoContent']/article[4]/div/div[1]/div/div[2]")));
            if (ReturnString(driver, (By.xpath("//html/body/header/h1"))).length() != 0) {
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.append("title", ReturnString(driver, (By.xpath("//html/body/header/h1"))))
                        .append("url", driver.getCurrentUrl())
                        .append("score",
                                ReturnString(driver,
                                        By.xpath(
                                                "//html/body/section[1]/article[1]/aside/hgroup/article[1]/i")))
                        .append("score_num",
                                ReturnString(driver, By.xpath(
                                        "//html/body/section[1]/article[1]/aside/hgroup/article[1]/span")))
                        .append("want_num",
                                ReturnString(driver,
                                        By.xpath(
                                                "//html/body/section[1]/article[1]/aside/hgroup/article[2]/i")))
                        .append("type",
                                ReturnString(driver, By.xpath("//html/body/section[1]/article[1]/aside/p[1]")))
                        .append("timing",
                                ReturnString(driver, By.xpath("//html/body/section[1]/article[1]/aside/p[2]")))
                        .append("system",
                                ReturnString(driver, By.xpath("//html/body/section[1]/article[1]/aside/p[3]")))
                        .append("onscreendate",
                                ReturnString(driver, By.xpath("//html/body/section[1]/article[1]/aside/p[4]")))
                        .append("total_rev",
                                ReturnString(driver, By.xpath("//html/body/section[1]/article[2]/span[1]")))
                        .append("firstweek_rev",
                                ReturnString(driver, By.xpath("//html/body/section[1]/article[2]/span[2]")))
                        .append("ahead_rev",
                                ReturnString(driver, By.xpath("//html/body/section[1]/article[2]/span[3]")))
                        .append("director", ReturnString(driver, By.xpath(
                                "//*[@id='infoContent']/article[@class='m-info-crews m-info-section']/div/div[1]/div/div[2]/div[1]/div[2]")))
                        .append("actor", ReturnString(driver, By.xpath(
                                "//*[@id='infoContent']/article[@class='m-info-crews m-info-section']/div/div[1]/div/div[2]/div[2]/div[2]")))
                        .append("production", ReturnString(driver, By.xpath(
                                "//*[@id='infoContent']/article[@class='production-companies m-info-section']/div/div[1]/div/div[2]")))
                        .append("jointproduction", ReturnString(driver, By.xpath(
                                "//*[@id='infoContent']/article[@class='joint-production-companies m-info-section']/div/div[1]/div/div[2]")))
                        .append("distribution", ReturnString(driver, By.xpath(
                                "//*[@id='infoContent']/article[@class='distribution-firm m-info-section']/div/div[1]/div/div[2]")))
                        .append("techpara", ReturnString(driver, By.xpath(
                                "//*[@id='infoContent']/article[tech-params m-info-section]/div/div[1]/div/div[2]")))
                        .append("infodrama", ReturnString(driver, By.xpath(
                                "//*[@id='infoContent']/article[m-info-drama m-info-section]/div/div[2]")))
                        .append("want_by_city", ReturnString(driver, By.xpath("//*[@id='wantCity']")));
                dbCollection.insert(dbObject);
                driver.close();
                driver.quit();
                mongoClient.close();
            }
        }
    };
    MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);
    // ?
    // DBCollection dbCollection =
    // mongoClient.getDB("maoyan_crawler").getCollection("rankings_am");
    DB db = mongoClient.getDB("maoyan_crawler");
    // ?????
    Set<String> colls = db.getCollectionNames();
    for (String s : colls) {
        // Collection(?"")
        if (s.equals("movie_store")) {
            db.getCollection(s).drop();
        }
    }

    // DBDBManager
    DBManager manager = new BerkeleyDBManager("maoyan");
    // Crawler?DBManagerExecutor
    for (int round = 200; round < 300; round++) {
        System.out.println("Round " + round + " crawling.../n");
        Crawler crawler = new Crawler(manager, executor);
        for (int i = 1 + 100 * round; i <= 100 + 100 * round; i++) {
            crawler.addSeed("http://pf.maoyan.com/movie/" + i + "?_v_=yes");
        }
        /* ??visit */
        crawler.setVisitInterval(50);
        /* ?http? */
        crawler.setRetryInterval(100);
        crawler.setThreads(10);
        crawler.start(1);
    }
}

From source file:com.maoyan.pf.webcollector.spider.ShowrateCrawler.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Executor executor = new Executor() {
        @Override//w w w  . j a v  a 2  s.co m
        public void execute(CrawlDatum datum, CrawlDatums next) throws Exception {
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            // ?
            // DBCollection dbCollection = mongoClient.getDB("maoyan_crawler").getCollection("rankings_am"); 
            DB db = mongoClient.getDB("maoyan_crawler");
            // ?????
            Set<String> colls = db.getCollectionNames();
            for (String s : colls) {
                // Collection(?"")
                if (s.equals("show_rate")) {
                    db.getCollection(s).drop();
                }
            }
            DBCollection dbCollection = db.getCollection("show_rate");
            //                ProfilesIni pi = new ProfilesIni();
            //                FirefoxProfile profile = pi.getProfile("default");
            WebDriver driver = new FirefoxDriver();
            driver.manage().window().maximize();
            driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS);
            //                driver.setJavascriptEnabled(false);
            System.out.println("??\n");
            driver.get(datum.getUrl());
            //                System.out.println(driver.getPageSource());
            List<WebElement> movie_name = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c1 lineDot']"));
            List<WebElement> boxoffice_rate = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c2 red']"));
            List<WebElement> visit_pershow = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c3 gray']"));
            WebElement title = driver.findElement(By.xpath("//p[@id='pieTip']"));
            for (int i = 0; i < movie_name.size(); i++) {
                String movie_name_val = movie_name.get(i).getText();
                String boxofficerate_val = boxoffice_rate.get(i).getText();
                String visit_pershow_val = visit_pershow.get(i).getText();
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.append("title", title.getText()).append("is_gold", "?")
                        .append("show_type", "?").append("movie_name", movie_name_val)
                        .append("boxoffice_rate", boxofficerate_val).append("visit_pershow", visit_pershow_val);
                dbCollection.insert(dbObject);
            }
            System.out.println("?\n");
            WebElement click_gold = driver.findElement(By.id("playPlan_time"));
            click_gold.click();
            String gold_seat = driver.getWindowHandle();
            driver.switchTo().window(gold_seat);
            List<WebElement> movie_name_gold = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c1 lineDot']"));
            List<WebElement> boxoffice_rate_gold = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c2 red']"));
            List<WebElement> visit_pershow_gold = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c3 gray']"));
            WebElement title_gold = driver.findElement(By.xpath("//p[@id='pieTip']"));
            for (int i = 0; i < movie_name_gold.size(); i++) {
                String movie_name_val = movie_name_gold.get(i).getText();
                String boxofficerate_val = boxoffice_rate_gold.get(i).getText();
                String visit_pershow_val = visit_pershow_gold.get(i).getText();
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.append("title", title_gold.getText()).append("is_gold", "")
                        .append("show_type", "?").append("movie_name", movie_name_val)
                        .append("boxoffice_rate", boxofficerate_val).append("visit_pershow", visit_pershow_val);
                dbCollection.insert(dbObject);
            }
            System.out.println("?\n");
            WebElement click_vist = driver.findElement(By.xpath("//*[@id='show--type']"));
            click_vist.click();
            String gold_vist = driver.getWindowHandle();
            driver.switchTo().window(gold_vist);
            List<WebElement> movie_name_gold_visit = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c1 lineDot']"));
            List<WebElement> boxoffice_rate_gold_visit = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c2 red']"));
            List<WebElement> visit_pershow_gold_visit = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c3 gray']"));
            WebElement title_gold_visit = driver.findElement(By.xpath("//p[@id='pieTip']"));
            for (int i = 0; i < movie_name_gold_visit.size(); i++) {
                String movie_name_val = movie_name_gold_visit.get(i).getText();
                String boxofficerate_val = boxoffice_rate_gold_visit.get(i).getText();
                String visit_pershow_val = visit_pershow_gold_visit.get(i).getText();
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.append("title", title_gold_visit.getText()).append("is_gold", "")
                        .append("show_type", "").append("movie_name", movie_name_val)
                        .append("boxoffice_rate", boxofficerate_val).append("visit_pershow", visit_pershow_val);
                dbCollection.insert(dbObject);
            }
            System.out.println("?\n");
            click_gold.click();
            String normal_seat = driver.getWindowHandle();
            driver.switchTo().window(normal_seat);
            List<WebElement> movie_name_normal_seat = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c1 lineDot']"));
            List<WebElement> boxoffice_rate_normal_seat = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c2 red']"));
            List<WebElement> visit_pershow_normal_seat = driver
                    .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c3 gray']"));
            WebElement title_normal_seat = driver.findElement(By.xpath("//p[@id='pieTip']"));
            for (int i = 0; i < movie_name_normal_seat.size(); i++) {
                String movie_name_val = movie_name_normal_seat.get(i).getText();
                String boxofficerate_val = boxoffice_rate_normal_seat.get(i).getText();
                String visit_pershow_val = visit_pershow_normal_seat.get(i).getText();
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.append("title", title_normal_seat.getText()).append("is_gold", "?")
                        .append("show_type", "").append("movie_name", movie_name_val)
                        .append("boxoffice_rate", boxofficerate_val).append("visit_pershow", visit_pershow_val);
                dbCollection.insert(dbObject);
            }

            driver.close();
            driver.quit();
            mongoClient.close();
        }
    };

    //DBDBManager
    DBManager manager = new BerkeleyDBManager("maoyan");
    //Crawler?DBManagerExecutor
    Crawler crawler = new Crawler(manager, executor);
    crawler.addSeed("http://pf.maoyan.com/show/rate");
    crawler.start(1);
}

From source file:com.mastfrog.acteur.mongo.util.UpdateBuilder.java

License:Open Source License

public BasicDBObject build() {
    BasicDBObject result = new BasicDBObject();
    if (!set.isEmpty()) {
        result.append("$set", new BasicDBObject(set));
    }/*from www  .  j  av  a 2s.  com*/
    if (!inc.isEmpty()) {
        result.append("$inc", new BasicDBObject(inc));
    }
    if (!push.isEmpty()) {
        result.append("$push", new BasicDBObject(push));
    }
    if (!pull.isEmpty()) {
        result.append("$pull", new BasicDBObject(push));
    }
    if (!unset.isEmpty()) {
        BasicDBList list = new BasicDBList();
        list.addAll(unset);
        result.append("$unset", list);
    }
    return result;
}

From source file:com.mebigfatguy.mongobrowser.actions.ManageIndicesAction.java

License:Apache License

private void updateIndices(DBCollection collection, List<IndexDescription> indices) {

    collection.dropIndexes();/*from w w  w  .jav  a  2s. co m*/

    for (IndexDescription index : indices) {
        if (!MongoConstants.ID_INDEX.equals(index.getIndexName())) {

            BasicDBObject dbFields = new BasicDBObject();
            IndexFieldList fieldList = index.getIndexFieldList();

            for (IndexField field : fieldList) {
                dbFields.append(field.getFieldName(), Integer.valueOf(field.isAscending() ? 1 : -1));
            }

            collection.ensureIndex(dbFields, index.getIndexName());
        }
    }
}

From source file:com.miya.twit.mongodb.DBConnectSentiment.java

public void insertWord(List<TweetDBEntity> list) {

    DBCollection collection = dbConnection();
    if (collection != null) {
        BasicDBObject document;

        for (TweetDBEntity twit : list) {
            document = new BasicDBObject();
            document.append("text", twit.getText());
            document.append("rootType", twit.getRootType());
            document.append("polarity", twit.getPolarity());
            collection.insert(document);
            System.out.println(collection.getCount() + " ---" + twit.getText() + " tweet'i yazld");
        }/*  www  . ja v  a  2 s  .  c o m*/
    }
}

From source file:com.miya.twit.mongodb.DBConnectSentiment.java

public void insertExpression(List<Expressions> list) {

    DBCollection collection = dbConnectionForExpression();
    if (collection != null) {
        BasicDBObject document;

        for (Expressions exp : list) {
            document = new BasicDBObject();
            document.append("text", exp.getExpression());
            document.append("polarity", Polarity.getPolarityValue(exp.getPolarity()));
            collection.insert(document);
            System.out.println(/*from ww  w.j  a v a 2s.com*/
                    collection.getCount() + "---------    " + Polarity.getPolarityValue(exp.getPolarity())
                            + " ---" + exp.getExpression() + " Deyim'i yazld");
        }
    }
}

From source file:com.mobileman.kuravis.core.services.treatment_review.impl.TreatmentReviewServiceImpl.java

License:Apache License

/**
 * Updates existing treatment review summary
 * @param treatmentReviewSummary//from   w ww .  j av a2  s.c  om
 * @param review
 * @param reviewAction
 * @return error string in case error, null otherwise
 */
@SuppressWarnings("unchecked")
private DBObject updateTreatmentReviewSummary(DBObject treatmentReviewSummary, DBObject user, DBObject review,
        String diseaseId, String treatmentId, CRUDAction reviewAction) {
    if (treatmentReviewSummary == null) {
        return null;
    }

    String gender = UserUtils.getGender(user);
    String trsid = (String) treatmentReviewSummary.get(EntityUtils.ID);

    DBCursor trCursor = findAllTreatmentReviews(diseaseId, treatmentId, TreatmentReview.RATING,
            TreatmentReview.SIDE_EFFECTS,
            //
            TreatmentReview.CURRENCY, TreatmentReview.DOCTOR_COSTS, TreatmentReview.TREATMENT_PRICE,
            TreatmentReview.TREATMENT_QUANTITY, TreatmentReview.INSURANCE_COVERED,
            TreatmentReview.INSURANCE_COVERAGE, TreatmentReview.COINSURANCE);

    // go through all reviews and count them based on their value (group it) + add rating of given review
    // go through all side effects and count them based on side effect name (group it) + add side effects of given review
    Map<Number, DBObject> ratingsCounts = new HashMap<Number, DBObject>();
    Map<String, DBObject> trsSideEffects = new HashMap<String, DBObject>();

    int reviewsCount = 0;
    int ratingsCount = 0;
    BigDecimal ratingSum = BigDecimal.ZERO;

    List<TreatmentCost> treatmentCosts = new ArrayList<TreatmentCost>();

    for (DBObject tmpReview : trCursor) {
        if (CRUDAction.DELETE.equals(reviewAction)
                && String.class.cast(review.get(ID)).equalsIgnoreCase((String) tmpReview.get(EntityUtils.ID))) {
            continue;
        }

        TreatmentCost treatmentCost = TreatmentCost.createFromReview(tmpReview);
        if (treatmentCost != null) {
            treatmentCosts.add(treatmentCost);
        }

        reviewsCount++;
        Number trRating = (Number) tmpReview.get(TreatmentReview.RATING);
        if (trRating != null) {
            ++ratingsCount;

            ratingSum = ratingSum.add(new BigDecimal(trRating.doubleValue()));

            if (!ratingsCounts.containsKey(trRating)) {
                ratingsCounts.put(trRating, new BasicDBObject(EntityUtils.NAME, trRating).append("count", 1));
            } else {
                incrementCount(ratingsCounts.get(trRating));
            }
        }

        List<DBObject> trSideEffects = (List<DBObject>) tmpReview.get(TreatmentReview.SIDE_EFFECTS);
        if (trSideEffects != null) {
            createTreatmentReviewSummarySideEffects(trSideEffects, trsSideEffects);
        }
    }

    BigDecimal ratingAvg = null;
    if (ratingsCount > 0) {
        ratingAvg = ratingSum.divide(new BigDecimal(ratingsCount), 5, BigDecimal.ROUND_HALF_EVEN);
    }

    if (reviewsCount == 0 && CRUDAction.DELETE.equals(reviewAction)) {
        // no reviews then remove summary
        getCollection(TreatmentReviewSummary.ENTITY_NAME).remove(new BasicDBObject(EntityUtils.ID, trsid));
        getCollection(EntityUtils.TREATMENT_SUMMARY_AGE_STATISTICS)
                .remove(new BasicDBObject("summaryId", trsid));
        getCollection(TreatmentCostStatistics.ENTITY_NAME)
                .remove(new BasicDBObject(TreatmentCostStatistics.SUMMARY_ID, trsid));
        getCollection(TreatmentDurationStatistics.ENTITY_NAME)
                .remove(new BasicDBObject(TreatmentCostStatistics.SUMMARY_ID, trsid));
    } else {
        DBObject setCommand = new BasicDBObject()
                .append(TreatmentReviewSummary.RATINGS, new ArrayList<>(ratingsCounts.values()))
                .append(TreatmentReviewSummary.SIDE_EFFECTS, new ArrayList<>(trsSideEffects.values()))
                .append(EntityUtils.MODIFIED_ON, new Date());
        BasicDBObject command = new BasicDBObject("$set", setCommand);

        if (ratingAvg != null) {
            setCommand.put(TreatmentReviewSummary.RATING, ratingAvg.doubleValue());
        } else {
            command.put("$unset", new BasicDBObject(TreatmentReviewSummary.RATING, ""));
        }

        int statsIncrement = 0;
        switch (reviewAction) {
        case CREATE:
            command.put("$unset", new BasicDBObject(TreatmentReviewSummary.SUGGESTION, ""));
            statsIncrement = 1;
            break;
        case DELETE:
            statsIncrement = -1;
            break;
        default:
            break;
        }

        if (statsIncrement != 0) {
            BasicDBObject incCommand = new BasicDBObject("reviewsCount", statsIncrement);
            if (user.get(User.ATTR_GENDER) != null) {
                incCommand.append("genderStatistics." + gender, statsIncrement);
            } else {
                incCommand.append("genderStatistics." + Gender.UNKNOWN.getValue(), statsIncrement);
            }

            command.append("$inc", incCommand);
        }

        getCollection(TreatmentReviewSummary.ENTITY_NAME).update(new BasicDBObject(EntityUtils.ID, trsid),
                command);

        for (Gender tmpgender : Gender.values()) {
            Query query = Query.query(Criteria.where("genderStatistics." + tmpgender.getValue()).lt(0));
            getCollection(TreatmentReviewSummary.ENTITY_NAME).update(query.getQueryObject(), new BasicDBObject(
                    "$set", new BasicDBObject("genderStatistics." + tmpgender.getValue(), 0)));
        }

        // handle YEAR_OF_BIRTH statistics - only in case CREATE or DELETE review
        if (statsIncrement != 0 && user.get(User.ATTR_YEAR_OF_BIRTH) != null) {
            boolean upsert = statsIncrement > 0;

            DBObject filter = QueryBuilder.start().put(EntityUtils.ID)
                    .is(trsid + user.get(User.ATTR_YEAR_OF_BIRTH) + gender).put("summaryId").is(trsid)
                    .and(User.ATTR_GENDER).is(gender).and(EntityUtils.NAME)
                    .is(user.get(User.ATTR_YEAR_OF_BIRTH)).get();

            command = new BasicDBObject("$inc", new BasicDBObject("count", statsIncrement));
            getCollection(EntityUtils.TREATMENT_SUMMARY_AGE_STATISTICS).update(filter, command, upsert, false);
        }
    }

    return null;
}