Example usage for com.mongodb WriteResult getN

List of usage examples for com.mongodb WriteResult getN

Introduction

In this page you can find the example usage for com.mongodb WriteResult getN.

Prototype

public int getN() 

Source Link

Document

Gets the "n" field, which contains the number of documents affected in the write operation.

Usage

From source file:org.canedata.provider.mongodb.entity.MongoEntity.java

License:Apache License

public int update(Serializable... keys) {
    if (logger.isDebug())
        logger.debug("Updating entitiy, Database is {0}, Collection is {1}, keys is {2}.", getSchema(),
                getName(), Arrays.toString(keys));

    try {//from   w ww  .  j  av a2s  .  c  o m
        if (keys == null || keys.length == 0)
            return 0;

        validateState();

        final BasicDBObject fields = new BasicDBObject();
        final BasicDBObject othersFields = new BasicDBObject();
        final BasicDBObject options = new BasicDBObject();

        getIntent().playback(new Tracer() {

            public Tracer trace(Step step) throws AnalyzeBehaviourException {
                switch (step.step()) {
                case MongoStep.PUT:
                    if (logger.isDebug())
                        logger.debug("Analyzing behivor PUT, step is {0}, purpose is {1}, scalar is {2}.",
                                step.step(), step.getPurpose(), Arrays.toString(step.getScalar()));

                    if (StringUtils.isBlank(step.getPurpose()))
                        break;

                    Object val = (step.getScalar() == null || step.getScalar().length == 0) ? null
                            : step.getScalar()[0];

                    if (step.getPurpose().matches(internalCmds))
                        othersFields.append(step.getPurpose(), val);
                    else
                        fields.append(step.getPurpose(), val);

                    break;
                case MongoStep.OPTION:
                    options.append(step.getPurpose(), step.getScalar()[0]);

                    break;
                default:
                    logger.warn("Step {0} does not apply to activities create, this step will be ignored.",
                            step.step());
                }

                return this;
            }

        });

        BasicDBObject fs = new BasicDBObject();
        if (!fields.isEmpty())
            fs.put("$set", fields);

        if (!othersFields.isEmpty())
            fs.putAll(othersFields.toMap());

        if (fs.isEmpty())
            return 0;

        WriteResult wr = getCollection().update(new BasicDBObject().append("_id", keys[0]), fs,
                options.getBoolean(Options.UPSERT, false), false, getCollection().getWriteConcern());
        if (!StringUtils.isBlank(wr.getError()))
            throw new DataAccessException(wr.getError());

        // invalidate cache
        if (null != getCache()) {
            String cacheKey = getKey().concat("#").concat(keys[0].toString());
            getCache().remove(cacheKey);

            if (logger.isDebug())
                logger.debug("Invalidated cache key is {0}.", keys[0].toString());
        }

        return wr.getN();
    } catch (AnalyzeBehaviourException abe) {
        if (logger.isDebug())
            logger.debug(abe, "Analyzing behaviour failure, cause by: {0}.", abe.getMessage());

        throw new RuntimeException(abe);
    } finally {
        getIntent().reset();
    }
}

From source file:org.canedata.provider.mongodb.entity.MongoEntity.java

License:Apache License

public int updateRange(Expression expr) {
    if (logger.isDebug())
        logger.debug("Updating entities, Database is {0}, Collection is {1} ...", getSchema(), getName());

    try {//from   w  w w.j  av  a  2  s  . c o m
        validateState();

        final BasicDBObject fields = new BasicDBObject();
        final BasicDBObject othersFields = new BasicDBObject();
        final BasicDBObject options = new BasicDBObject();

        getIntent().playback(new Tracer() {

            public Tracer trace(Step step) throws AnalyzeBehaviourException {
                switch (step.step()) {
                case MongoStep.PUT:
                    if (StringUtils.isBlank(step.getPurpose()))
                        break;

                    Object val = (step.getScalar() == null || step.getScalar().length == 0) ? null
                            : step.getScalar()[0];

                    if (step.getPurpose().matches(internalCmds))
                        othersFields.append(step.getPurpose(), val);
                    else
                        fields.append(step.getPurpose(), val);

                    break;
                case MongoStep.OPTION:
                    options.append(step.getPurpose(), step.getScalar()[0]);

                    break;
                default:
                    logger.warn("Step {0} does not apply to activities create, this step will be ignored.",
                            step.step());
                }

                return this;
            }

        });

        final MongoExpressionFactory expFactory = new MongoExpressionFactory.Impl();
        BasicDBObject query = expFactory.parse((MongoExpression) expr);

        if (logger.isDebug())
            logger.debug("Updating entities, Database is {0}, Collection is {1}, expression is {2} ...",
                    getSchema(), getName(), query.toString());

        BasicDBObject fs = new BasicDBObject();
        if (!fields.isEmpty())
            fs.append("$set", fields);

        if (!othersFields.isEmpty())
            fs.putAll(othersFields.toMap());

        if (fs.isEmpty())
            return 0;

        WriteResult wr = getCollection().update(query, fs, options.getBoolean(Options.UPSERT, false), true,
                getCollection().getWriteConcern());
        if (!StringUtils.isBlank(wr.getError()))
            throw new DataAccessException(wr.getError());

        // invalidate cache
        if (null != getCache()) {
            invalidateCache(query);
        }

        return wr.getN();
    } catch (AnalyzeBehaviourException abe) {
        if (logger.isDebug())
            logger.debug(abe, "Analyzing behaviour failure, cause by: {0}.", abe.getMessage());

        throw new RuntimeException(abe);
    } finally {
        getIntent().reset();
    }
}

From source file:org.canedata.provider.mongodb.entity.MongoEntity.java

License:Apache License

public int delete(Serializable... keys) {
    if (keys == null || keys.length == 0) {
        logger.warn("System does not know what data you want to update, "
                + "you must specify the data row identity.");

        return 0;
    }/*from   w  w w .j a v  a 2s.com*/

    if (logger.isDebug())
        logger.debug("Deleting entitiy, Database is {0}, Collection is {1}, keys is {2}.", getSchema(),
                getName(), Arrays.toString(keys));

    try {
        validateState();

        WriteResult wr = getCollection().remove(new BasicDBObject().append("_id", keys[0]),
                getCollection().getWriteConcern());
        if (!StringUtils.isBlank(wr.getError()))
            throw new DataAccessException(wr.getError());

        // invalidate cache
        if (null != getCache()) {
            String cacheKey = getKey().concat("#").concat(keys[0].toString());
            getCache().remove(cacheKey);

            if (logger.isDebug())
                logger.debug("Invalidated cache key is {0}.", keys[0].toString());
        }

        return wr.getN();
    } finally {
        getIntent().reset();
    }
}

From source file:org.canedata.provider.mongodb.entity.MongoEntity.java

License:Apache License

public int deleteRange(Expression expr) {
    if (logger.isDebug())
        logger.debug("Deleting entities, Database is {0}, Collection is {1} ...", getSchema(), getName());

    try {//from   ww w  . j a va2  s  .c  o  m
        validateState();

        final MongoExpressionFactory expFactory = new MongoExpressionFactory.Impl();
        BasicDBObject query = expFactory.parse((MongoExpression) expr);

        if (logger.isDebug())
            logger.debug("Deleting entities, Database is {0}, Collection is {1}, expression is {2} ...",
                    getSchema(), getName(), query.toString());

        // invalidate cache
        if (null != getCache()) {
            invalidateCache(query);
        }

        WriteResult wr = getCollection().remove(query, getCollection().getWriteConcern());
        if (!StringUtils.isBlank(wr.getError()))
            throw new DataAccessException(wr.getError());

        return wr.getN();
    } catch (AnalyzeBehaviourException abe) {
        if (logger.isDebug())
            logger.debug(abe, "Analyzing behaviour failure, cause by: {0}.", abe.getMessage());

        throw new RuntimeException(abe);
    } finally {
        getIntent().reset();
    }
}

From source file:org.craftercms.social.repositories.system.impl.ContextPreferencesRepositoryImpl.java

License:Open Source License

@Override
public boolean saveEmailTemplate(final String context, final String type, final String template)
        throws SocialException {
    try {/*from  w  ww.ja  v a  2 s . com*/
        String findQ = getQueryFor("social.system.preferences.byContextAndTemplateType");
        String updateQ = getQueryFor("social.system.preferences.updateContextTemplateType");
        WriteResult r = getCollection().update(findQ, context, type.toUpperCase()).with(updateQ, template);

        return r.getN() == 1;
    } catch (MongoException ex) {
        throw new SocialException("Unable to update Email template", ex);
    }
}

From source file:org.edgexfoundry.dao.ScrubDao.java

License:Apache License

/**
 * Remove all pushed events and their associated readings
 *//*w w w  .  ja  va 2s . co m*/
public int scrubPushedEvents() {
    Query scrubQuery = new Query();
    scrubQuery.addCriteria(Criteria.where("pushed").gt(0));
    // remove readings
    template.remove(scrubQuery, Reading.class);
    // now remove events
    WriteResult result = template.remove(scrubQuery, Event.class);
    return result.getN();
}

From source file:org.edgexfoundry.dao.ScrubDao.java

License:Apache License

/**
 * remove all old events (and associated reaadings) based on delimiting age.
 * /*from  w w w.j  a  v  a  2s  . c  om*/
 * @param age - minimum age in milliseconds (from created timestamp) an event should be in order
 *        to be removed
 * @return - number of events removed
 */
public int scrubOldEvents(long age) {
    Query scrubQuery = new Query();
    scrubQuery.addCriteria(Criteria.where("created").lt(Calendar.getInstance().getTimeInMillis() - age));
    // remove readings
    template.remove(scrubQuery, Reading.class);
    // now remove events
    WriteResult result = template.remove(scrubQuery, Event.class);
    return result.getN();
}

From source file:org.geogit.storage.mongo.MongoObjectDatabase.java

License:Open Source License

private long deleteChunk(List<ObjectId> ids) {
    List<String> idStrings = Lists.transform(ids, Functions.toStringFunction());
    DBObject query = BasicDBObjectBuilder.start().push("oid").add("$in", idStrings).pop().get();
    WriteResult result = collection.remove(query);
    return result.getN();
}

From source file:org.jewzaam.mongo.Result.java

License:Open Source License

public Result(WriteResult result) {
    error = result.getError();
    count = result.getN();
}

From source file:org.jumpmind.symmetric.io.MongoDatabaseWriter.java

License:Open Source License

protected LoadStatus upsert(CsvData data) {
    statistics.get(batch).startTimer(DataWriterStatisticConstants.DATABASEMILLIS);
    try {//  w  w w .  j av a2  s. com
        DB db = clientManager.getDB(objectMapper.mapToDatabase(this.targetTable));
        DBCollection collection = db.getCollection(objectMapper.mapToCollection(this.targetTable));
        String[] columnNames = sourceTable.getColumnNames();
        Map<String, String> newData = data.toColumnNameValuePairs(columnNames, CsvData.ROW_DATA);
        Map<String, String> oldData = data.toColumnNameValuePairs(columnNames, CsvData.OLD_DATA);
        Map<String, String> pkData = data.toKeyColumnValuePairs(this.sourceTable);
        DBObject query = objectMapper.mapToDBObject(sourceTable, newData, oldData, pkData, true);
        DBObject object = objectMapper.mapToDBObject(sourceTable, newData, oldData, pkData, false);
        WriteResult results = collection.update(query, object, true, false, WriteConcern.ACKNOWLEDGED);
        if (results.getN() == 1) {
            return LoadStatus.SUCCESS;
        } else {
            throw new SymmetricException("Failed to write data: " + object.toString());
        }
    } finally {
        statistics.get(batch).stopTimer(DataWriterStatisticConstants.DATABASEMILLIS);
    }
}