Java 类com.mongodb.client.result.UpdateResult 实例源码

项目:GitHub    文件:Repositories.java   
protected final FluentFuture<Integer> doUpdate(
        final Constraints.ConstraintHost criteria,
        final Constraints.Constraint update,
        final UpdateOptions options) {

  checkNotNull(criteria, "criteria");
  checkNotNull(update, "update");
  checkNotNull(options, "options");

  return submit(new Callable<UpdateResult>() {
    @Override
    public UpdateResult call() {
      return collection()
          .updateMany(
          convertToBson(criteria),
          convertToBson(update),
          options);
    }
  }).lazyTransform(new Function<UpdateResult, Integer>() {
    @Override
    public Integer apply(UpdateResult input) {
      return (int) input.getModifiedCount();
    }
  });
}
项目:mongodb-crud    文件:UpdateDocumentsImpl.java   
/**
 * This method update all the matches document
 */
@Override
public void updateManyDocument() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    Bson filter = null;
    Bson query = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());
        filter = eq("name", "Sundar");
        query = combine(set("age", 23), set("gender", "Male"));
        UpdateResult result = collection.updateMany(filter, query);
        log.info("UpdateMany Status : " + result.wasAcknowledged());
        log.info("No of Record Modified : " + result.getModifiedCount());
    } catch (MongoException e) {
        log.error("Exception occurred while update Many Document : " + e, e);
    }
}
项目:mongodb-crud    文件:UpdateDocumentsImpl.java   
/**
 * This method update document with lastmodified properties 
 */
@Override
public void updateDocumentWithCurrentDate() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    Bson filter = null;
    Bson query = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());
        filter = eq("name", "Sundar");
        query = combine(set("age", 23), set("gender", "Male"),
                currentDate("lastModified"));
        UpdateResult result = collection.updateOne(filter, query);
        log.info("Update with date Status : " + result.wasAcknowledged());
        log.info("No of Record Modified : " + result.getModifiedCount());
    } catch (MongoException e) {
        log.error("Exception occurred while update Many Document with Date : " + e, e);
    }
}
项目:grain    文件:MongodbManager.java   
/**
 * 修改记录
 * 
 * @param collectionName
 *            表名
 * @param mongoObj
 *            对象
 * @return
 */
public static boolean updateById(String collectionName, MongoObj mongoObj) {
    MongoCollection<Document> collection = getCollection(collectionName);
    try {
        Bson filter = Filters.eq(MongoConfig.MONGO_ID, mongoObj.getDocument().getObjectId(MongoConfig.MONGO_ID));
        mongoObj.setDocument(null);
        Document document = objectToDocument(mongoObj);
        UpdateResult result = collection.updateOne(filter, new Document(MongoConfig.$SET, document));
        if (result.getMatchedCount() == 1) {
            return true;
        } else {
            return false;
        }
    } catch (Exception e) {
        if (log != null) {
            log.error("修改记录失败", e);
        }
        return false;
    }

}
项目:otus-api    文件:ActivityConfigurationDaoBean.java   
@Override
public ActivityCategory update(ActivityCategory activityCategory) throws DataNotFoundException {
    BasicDBObject query = new BasicDBObject();
    query.put("objectType", "ActivityCategory");
    query.put("name", activityCategory.getName());

    UpdateResult updateResult = collection.updateOne(query,
            new Document("$set", new Document("label",activityCategory.getLabel())), new UpdateOptions().upsert(false));

    if (updateResult.getMatchedCount() == 0){
        throw new DataNotFoundException(
                new Throwable("ActivityCategory {" + activityCategory.getName() + "} not found."));
    }

    return activityCategory;
}
项目:otus-api    文件:ActivityConfigurationDaoBean.java   
@Override
public void setNewDefault(String name) throws DataNotFoundException {
    BasicDBObject query = new BasicDBObject();
    query.put("objectType", "ActivityCategory");
    query.put("isDefault", true);
    UpdateResult undefaultResult = collection.updateOne(query, new Document("$set", new Document("isDefault", false)), new UpdateOptions().upsert(false));

    if (undefaultResult.getMatchedCount() > 1){
        throw new DataNotFoundException(
                new Throwable("Default category error. More than one default found"));
    }

    BasicDBObject otherQuery = new BasicDBObject();
    otherQuery.put("objectType", "ActivityCategory");
    otherQuery.put("name", name);
    UpdateResult defaultSetResult = collection.updateOne(otherQuery, new Document("$set", new Document("isDefault", true)), new UpdateOptions().upsert(false));

    if (defaultSetResult.getMatchedCount() == 0){
        throw new DataNotFoundException(
                new Throwable("ActivityCategory {" + name + "} not found."));
    }

}
项目:otus-api    文件:ParticipantLaboratoryDaoBean.java   
@Override
public Tube updateTubeCollectionData(long rn,Tube tube) throws DataNotFoundException {
    Document parsedCollectionData = Document.parse(TubeCollectionData.serialize(tube.getTubeCollectionData()));

    UpdateResult updateLabData = collection.updateOne(and(eq("recruitmentNumber", rn),
                                                            eq("tubes.code",tube.getCode())),
                                                        set("tubes.$.tubeCollectionData", parsedCollectionData),
                                                        new UpdateOptions().upsert(false));

    if (updateLabData.getMatchedCount() == 0) {
        throw new DataNotFoundException(new Throwable("Laboratory of Participant recruitment number: " + rn
                + " does not exists."));
    }

    return tube;
}
项目:ibm-performance-monitor    文件:ProfiledMongoCollection.java   
@Override
public UpdateResult updateMany(Bson filter, Bson arg1)
{
    int writeSize = 0;
    OperationMetric metric = null;
    if (MongoLogger.GATHERER.isEnabled())
    {
        List<String> keyValuePairs = MongoUtilities.getKeyValuePairs(filter);
        keyValuePairs.add("update");
        keyValuePairs.add(arg1.toString());
        String operationName = "Mongo : " + getNamespace().getCollectionName() + " : updateMany : " +
            MongoUtilities.filterParameters(filter);
        metric = startMetric(operationName, keyValuePairs);
        addWriteConcern(metric);
    }

    UpdateResult retVal = collection.updateMany(filter, arg1);

    insertUpdateResultProperties(metric, retVal);

    stopMetric(metric, writeSize);

    return retVal;
}
项目:ibm-performance-monitor    文件:ProfiledMongoCollection.java   
@Override
public UpdateResult updateMany(Bson filter, Bson arg1, UpdateOptions arg2)
{
    int writeSize = 0;
    OperationMetric metric = null;
    if (MongoLogger.GATHERER.isEnabled())
    {
        List<String> keyValuePairs = MongoUtilities.getKeyValuePairs(filter);
        keyValuePairs.add("update");
        keyValuePairs.add(arg1.toString());
        String operationName = "Mongo : " + getNamespace().getCollectionName() + " : updateMany : " +
            MongoUtilities.filterParameters(filter);
        metric = startMetric(operationName, keyValuePairs);
        addWriteConcern(metric);
    }

    UpdateResult retVal = collection.updateMany(filter, arg1, arg2);

    insertUpdateResultProperties(metric, retVal);

    stopMetric(metric, writeSize);

    return retVal;
}
项目:ibm-performance-monitor    文件:ProfiledMongoCollection.java   
@Override
public UpdateResult updateOne(Bson filter, Bson arg1)
{
    int writeSize = 0;
    OperationMetric metric = null;
    if (MongoLogger.GATHERER.isEnabled())
    {
        List<String> keyValuePairs = MongoUtilities.getKeyValuePairs(filter);
        keyValuePairs.add("update");
        keyValuePairs.add(arg1.toString());
        String operationName = "Mongo : " + getNamespace().getCollectionName() + " : updateOne : " +
            MongoUtilities.filterParameters(filter);
        metric = startMetric(operationName, keyValuePairs);
        addWriteConcern(metric);
    }

    UpdateResult retVal = collection.updateOne(filter, arg1);

    insertUpdateResultProperties(metric, retVal);

    stopMetric(metric, writeSize);

    return retVal;
}
项目:ibm-performance-monitor    文件:ProfiledMongoCollection.java   
@Override
public UpdateResult updateOne(Bson filter, Bson arg1, UpdateOptions arg2)
{
    int writeSize = 0;
    OperationMetric metric = null;
    if (MongoLogger.GATHERER.isEnabled())
    {
        List<String> keyValuePairs = MongoUtilities.getKeyValuePairs(filter);
        keyValuePairs.add("update");
        keyValuePairs.add(arg1.toString());
        String operationName = "Mongo : " + getNamespace().getCollectionName() + " : updateOne : " +
            MongoUtilities.filterParameters(filter);
        metric = startMetric(operationName, keyValuePairs);
        addWriteConcern(metric);
    }

    UpdateResult retVal = collection.updateOne(filter, arg1, arg2);

    insertUpdateResultProperties(metric, retVal);

    stopMetric(metric, writeSize);

    return retVal;
}
项目:hawkcd    文件:MongoDbRepository.java   
@Override
public T update(T entry) {
    if (entry == null) {
        return null;
    }

    try {
        String entryToJson = this.jsonConverter.toJson(entry);
        Document document = Document.parse(entryToJson);

        UpdateResult updateResult = this.collection.replaceOne(eq("id", document.get("id")), document);

        if (updateResult.getMatchedCount() == 1) { // means one record updated
            return entry;
        }

        return null; //either none or many records updated, so consider the operation not successful.
    } catch (RuntimeException e) {
        LOGGER.error(e);
        return null;
    }
}
项目:jpa-unit    文件:RefreshOperation.java   
@Override
public void execute(final MongoDatabase connection, final Document data) {
    for (final String collectionName : data.keySet()) {
        final MongoCollection<Document> collection = connection.getCollection(collectionName);

        @SuppressWarnings("unchecked")
        final List<Document> documents = data.get(collectionName, List.class);

        for (final Document doc : documents) {
            final UpdateResult result = collection.replaceOne(Filters.eq(doc.get("_id")), doc);

            if (result.getMatchedCount() == 0) {
                collection.insertOne(doc);
            }
        }
    }
}
项目:Camel    文件:MongoDbProducer.java   
private Function<Exchange, Object> createDoSave() {
    return exchange1 -> {
        try {
            MongoCollection<BasicDBObject> dbCol = calculateCollection(exchange1);
            BasicDBObject saveObj = exchange1.getIn().getMandatoryBody(BasicDBObject.class);

            UpdateOptions options = new UpdateOptions().upsert(true);
            BasicDBObject queryObject = new BasicDBObject("_id", saveObj.get("_id"));
            UpdateResult result = dbCol.replaceOne(queryObject, saveObj, options);
            exchange1.getIn().setHeader(MongoDbConstants.OID, saveObj.get("_id"));
            return result;
        } catch (InvalidPayloadException e) {
            throw new CamelMongoDbException("Body incorrect type for save", e);
        }
    };
}
项目:Camel    文件:MongoDbOperationsTest.java   
@Test
public void testSave() throws Exception {
    // Prepare test
    assertEquals(0, testCollection.count());
    Object[] req = new Object[] {"{\"_id\":\"testSave1\", \"scientist\":\"Einstein\"}", "{\"_id\":\"testSave2\", \"scientist\":\"Copernicus\"}"};
    Object result = template.requestBody("direct:insert", req);
    assertTrue(result instanceof List);
    assertEquals("Number of records persisted must be 2", 2, testCollection.count());

    // Testing the save logic
    DBObject record1 = testCollection.find(new BasicDBObject("_id", "testSave1")).first();
    assertEquals("Scientist field of 'testSave1' must equal 'Einstein'", "Einstein", record1.get("scientist"));
    record1.put("scientist", "Darwin");

    result = template.requestBody("direct:save", record1);
    assertTrue(result instanceof UpdateResult);

    record1 = testCollection.find(new BasicDBObject("_id", "testSave1")).first();
    assertEquals("Scientist field of 'testSave1' must equal 'Darwin' after save operation", "Darwin", record1.get("scientist"));

}
项目:render    文件:RenderDao.java   
public void updateZForSection(final StackId stackId,
                              final String sectionId,
                              final Double z)
        throws IllegalArgumentException, IllegalStateException {

    MongoUtil.validateRequiredParameter("stackId", stackId);
    MongoUtil.validateRequiredParameter("sectionId", sectionId);
    MongoUtil.validateRequiredParameter("z", z);

    final MongoCollection<Document> tileCollection = getTileCollection(stackId);
    final Document query = new Document("layout.sectionId", sectionId);
    final Document update = new Document("$set", new Document("z", z));

    final UpdateResult result = tileCollection.updateMany(query, update);

    LOG.debug("updateZForSection: updated {} tile specs with {}.update({},{})",
              result.getModifiedCount(), MongoUtil.fullName(tileCollection), query.toJson(), update.toJson());
}
项目:render    文件:RenderDao.java   
public void updateZForTiles(final StackId stackId,
                            final Double z,
                            final List<String> tileIds)
        throws IllegalArgumentException, IllegalStateException {

    MongoUtil.validateRequiredParameter("stackId", stackId);
    MongoUtil.validateRequiredParameter("z", z);
    MongoUtil.validateRequiredParameter("tileIds", tileIds);

    final MongoCollection<Document> tileCollection = getTileCollection(stackId);
    final Document query = new Document("tileId", new Document("$in", tileIds));
    final Document update = new Document("$set", new Document("z", z));

    final UpdateResult result = tileCollection.updateMany(query, update);

    final String shortQueryForLog = "{ 'tileId': { '$in': [ " + tileIds.size() + " tile ids ... ] } }";
    LOG.debug("updateZForTiles: updated {} tile specs with {}.update({},{})",
              result.getModifiedCount(), MongoUtil.fullName(tileCollection), shortQueryForLog, update.toJson());
}
项目:fiware-cygnus    文件:MongoBackendImpl.java   
private void insertContextDataAggregatedForResoultion(String dbName, String collectionName,
        GregorianCalendar calendar, String entityId, String entityType, String attrName, String attrType,
        double max, double min, double sum, double sum2, int numSamples, Resolution resolution) {
    // Get database and collection
    MongoDatabase db = getDatabase(dbName);
    MongoCollection collection = db.getCollection(collectionName);

    // Build the query
    BasicDBObject query = buildQueryForInsertAggregated(calendar, entityId, entityType, attrName, resolution);

    // Prepopulate if needed
    BasicDBObject insert = buildInsertForPrepopulate(attrType, resolution, true);
    UpdateResult res = collection.updateOne(query, insert, new UpdateOptions().upsert(true));

    if (res.getMatchedCount() == 0) {
        LOGGER.debug("Prepopulating data, database=" + dbName + ", collection=" + collectionName + ", query="
                + query.toString() + ", insert=" + insert.toString());
    } // if

    // Do the update
    BasicDBObject update = buildUpdateForUpdate(attrType, calendar, max, min, sum, sum2, numSamples);
    LOGGER.debug("Updating data, database=" + dbName + ", collection=" + collectionName + ", query="
            + query.toString() + ", update=" + update.toString());
    collection.updateOne(query, update);
}
项目:cherimodata    文件:EntityInvocationHandler.java   
/**
 * stores the given EntityInvocationHandler represented Entity in the given Collection
 *
 * @param handler EntityInvocationHandler (Entity) to save
 * @param coll MongoCollection to save entity into
 */
@SuppressWarnings( "unchecked" )
static <T extends Entity> void save( EntityInvocationHandler handler, MongoCollection<T> coll )
{
    for ( ParameterProperty cpp : handler.properties.getValidationProperties() )
    {
        cpp.validate( handler.data.get( cpp.getMongoName() ) );
    }
    BsonDocumentWrapper wrapper = new BsonDocumentWrapper<>( handler.proxy,
        (org.bson.codecs.Encoder<Entity>) coll.getCodecRegistry().get( handler.properties.getEntityClass() ) );
    UpdateResult res = coll.updateOne(
        new BsonDocument( "_id",
            BsonDocumentWrapper.asBsonDocument( EntityCodec._obtainId( handler.proxy ), idRegistry ) ),
        new BsonDocument( "$set", wrapper ), new UpdateOptions() );
    if ( res.getMatchedCount() == 0 )
    {
        // TODO this seems too nasty, there must be a better way.for now live with it
        coll.insertOne( (T) handler.proxy );
    }
    handler.persist();
}
项目:immutables    文件:Repositories.java   
protected final FluentFuture<Integer> doUpdate(
        final Constraints.ConstraintHost criteria,
        final Constraints.Constraint update,
        final UpdateOptions options) {

  checkNotNull(criteria, "criteria");
  checkNotNull(update, "update");
  checkNotNull(options, "options");

  return submit(new Callable<UpdateResult>() {
    @Override
    public UpdateResult call() {
      return collection()
          .updateMany(
          convertToBson(criteria),
          convertToBson(update),
          options);
    }
  }).lazyTransform(new Function<UpdateResult, Integer>() {
    @Override
    public Integer apply(UpdateResult input) {
      return (int) input.getModifiedCount();
    }
  });
}
项目:mongodb-crud    文件:UpdateDocumentsImpl.java   
/**
 * This method update only one one document which is matched first
 */
@Override
public void updateOneDocument() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    Bson filter = null;
    Bson query = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());
        filter = eq("name", "Sundar");
        query = combine(set("age", 23), set("gender", "Male"));
        UpdateResult result = collection.updateOne(filter, query);
        log.info("UpdateOne Status : " + result.wasAcknowledged());
        log.info("No of Record Modified : " + result.getModifiedCount());
    } catch (MongoException e) {
        log.error("Exception occurred while update single Document : " + e, e);
    }
}
项目:rocketmq-flink-plugin    文件:MongoManager.java   
/**
 * @param dbName         库名
 * @param collectionName 表名
 * @param json1          条件
 * @param json2          保存doc
 * @return 更新结果信息
 */
public JSONObject executeUpdate(String dbName, String collectionName, JSONObject json1, JSONObject json2) {
    JSONObject resp = new JSONObject();
    try {
        MongoDatabase db = mongoClient.getDatabase(dbName);
        MongoCollection coll = db.getCollection(collectionName);
        JSONObject saveJson = new JSONObject();
        saveJson.put("$set", json2);
        Document doc1 = Document.parse(json1.toString());
        Document doc2 = Document.parse(saveJson.toString());
        UpdateResult ur = coll.updateOne(doc1, doc2);
        System.out.println("doc1 = " + doc1.toString());
        System.out.println("doc2 = " + doc2.toString());
        if (ur.isModifiedCountAvailable()) {
            if (json1.containsKey(ID)) {
                resp.put("Data", json1.get(ID));
            } else {
                resp.put("Data", json1);
            }
        }
    } catch (MongoTimeoutException e1) {
        e1.printStackTrace();
        resp.put("ReasonMessage", e1.getClass() + ":" + e1.getMessage());
        return resp;
    } catch (Exception e) {
        e.printStackTrace();
        resp.put("ReasonMessage", e.getClass() + ":" + e.getMessage());
    }
    return resp;
}
项目:rocketmq-flink-plugin    文件:MongoManager.java   
/**
 * @param dbName         库名
 * @param collectionName 集合名
 * @param json1          条件
 * @param json2          保存doc
 * @return upsert结果信息
 */
public JSONObject executeUpsert(String dbName, String collectionName, JSONObject json1, JSONObject json2) {
    JSONObject resp = new JSONObject();
    try {
        MongoDatabase db = mongoClient.getDatabase(dbName);
        MongoCollection coll = db.getCollection(collectionName);
        JSONObject saveJson = new JSONObject();
        saveJson.put("$set", json2);
        Document doc1 = Document.parse(json1.toString());
        Document doc2 = Document.parse(saveJson.toString());
        UpdateOptions up = new UpdateOptions();
        up.upsert(true);
        UpdateResult ur = coll.updateOne(doc1, doc2, up);
        if (ur.isModifiedCountAvailable()) {
            if (json1.containsKey(ID)) {
                resp.put("Data", json1.get(ID));
            } else {
                resp.put("Data", json1);
            }
        }
    } catch (MongoTimeoutException e1) {
        e1.printStackTrace();
        resp.put("ReasonMessage", e1.getClass() + ":" + e1.getMessage());
        return resp;
    } catch (Exception e) {
        e.printStackTrace();
        resp.put("ReasonMessage", e.getClass() + ":" + e.getMessage());
    }
    return resp;
}
项目:dooo    文件:MongodbDataAccess.java   
/**
 * 新增或者更新
 *
 * @param collectionName 集合名
 * @param query          查询条件
 * @param descData       目标数据
 * @return
 */
public boolean upsert(String collectionName, MongodbQuery query, Map<String, Object> descData) {
    MongoCollection collection = sMongoDatabase.getCollection(collectionName);
    UpdateOptions options = new UpdateOptions();
    options.upsert(true);
    BasicDBObject updateSetValue = new BasicDBObject("$set", descData);
    UpdateResult updateResult = collection.updateMany(query.getQuery(), updateSetValue, options);
    return updateResult.getUpsertedId() != null ||
            (updateResult.getMatchedCount() > 0 && updateResult.getModifiedCount() > 0);
}
项目:Java-9-Programming-Blueprints    文件:NoteResource.java   
@PUT
@Path("{id}")
public Response updateNote(Note note) {
    note.setModified(LocalDateTime.now());
    note.setUser(user.getId());
    UpdateResult result = 
            collection.updateOne(buildQueryById(note.getId()),
            new Document("$set", note.toDocument()));
    if (result.getModifiedCount() == 0) {
        return Response.status(Response.Status.NOT_FOUND).build();
    } else {
        return Response.ok().build();
    }
}
项目:mongodb-performance-test    文件:UpdateOperation.java   
@Override
long executeQuery(int threadId, long threadRunCount, long globalRunCount, long selectorId, long randomId){

    final Document doc = new Document("$set", new Document(RANDOM_LONG, randomId))
            .append("$inc", new Document(VERSION, 1));

    final UpdateResult res = THREAD_RUN_COUNT.equals(queriedField)?mongoCollection.updateMany(eq(queriedField, selectorId), doc)
            :ID.equals(queriedField)?mongoCollection.updateOne(eq(queriedField, selectorId), doc):null;
    return res!=null?res.getModifiedCount():0l;
}
项目:otus-api    文件:ActivityDaoBean.java   
@Override
public SurveyActivity update(SurveyActivity surveyActivity) throws DataNotFoundException {
    Document parsed = Document.parse(SurveyActivity.serialize(surveyActivity));
    parsed.remove("_id");
    UpdateResult updateOne = collection.updateOne(eq("_id", surveyActivity.getActivityID()),
            new Document("$set", parsed), new UpdateOptions().upsert(false));

    if (updateOne.getMatchedCount() == 0) {
        throw new DataNotFoundException(
                new Throwable("OID {" + surveyActivity.getActivityID().toString() + "} not found."));
    }

    return surveyActivity;
}
项目:otus-api    文件:ActivityDaoBean.java   
@Override
public void updateCategory(ActivityCategory activityCategory){
    Document query = new Document();
    query.put("category.name", activityCategory.getName());

    UpdateResult updateResult = collection.updateOne(query, new Document("$set", new Document("category.label", activityCategory.getLabel())), new UpdateOptions().upsert(false));

}
项目:otus-api    文件:ActivityConfigurationDaoBean.java   
@Override
public void disable(String name) throws DataNotFoundException {
    BasicDBObject query = new BasicDBObject();
    query.put("objectType", "ActivityCategory");
    query.put("name", name);

    UpdateResult updateResult = collection.updateOne(query, new Document("$set", new Document("disabled", true)), new UpdateOptions().upsert(false));

    if (updateResult.getMatchedCount() == 0) {
        throw new DataNotFoundException(
                new Throwable("ActivityCategory {" + name + "} not found."));        }
}
项目:otus-api    文件:ExamLotDaoBean.java   
@Override
public ExamLot update(ExamLot examLot) throws DataNotFoundException {
    Document parsed = Document.parse(ExamLot.serialize(examLot));
    parsed.remove("_id");

    UpdateResult updateLotData = collection.updateOne(eq("code", examLot.getCode()), new Document("$set", parsed),
            new UpdateOptions().upsert(false));

    if (updateLotData.getMatchedCount() == 0) {
        throw new DataNotFoundException(new Throwable("Exam Lot not found"));
    }

    return examLot;
}
项目:otus-api    文件:TransportationLotDaoBean.java   
@Override
public TransportationLot update(TransportationLot transportationLot) throws DataNotFoundException {
    Document parsed = Document.parse(TransportationLot.serialize(transportationLot));
    parsed.remove("_id");

    UpdateResult updateLotData = collection.updateOne(eq("code", transportationLot.getCode()),
            new Document("$set", parsed), new UpdateOptions().upsert(false));

    if (updateLotData.getMatchedCount() == 0) {
        throw new DataNotFoundException(
                new Throwable("Transportation Lot not found"));
    }

    return transportationLot;
}
项目:otus-api    文件:ParticipantLaboratoryDaoBean.java   
@Override
public ParticipantLaboratory updateLaboratoryData(ParticipantLaboratory labParticipant) throws DataNotFoundException {
    Document parsed = Document.parse(ParticipantLaboratory.serialize(labParticipant));
    parsed.remove("_id");

    UpdateResult updateLabData = collection.updateOne(eq("recruitmentNumber", labParticipant.getRecruitmentNumber()), new Document("$set", parsed),
            new UpdateOptions().upsert(false));

    if (updateLabData.getMatchedCount() == 0) {
        throw new DataNotFoundException(new Throwable("Laboratory of Participant recruitment number: " + labParticipant.getRecruitmentNumber()
                + " does not exists."));
    }

    return labParticipant;
}
项目:otus-api    文件:LaboratoryConfigurationDaoBean.java   
@Override
public void update(LaboratoryConfiguration configuration) throws Exception {
    Document parsed = Document.parse(LaboratoryConfiguration.serialize(configuration));
    parsed.remove("_id");

    UpdateResult updatedData = collection.updateOne(eq("_id", configuration.getId()), new Document("$set", parsed),
            new UpdateOptions().upsert(false));

    if (updatedData.getModifiedCount() == 0) {
        throw new Exception("Update was not executed.");
    }
}
项目:pumbaa    文件:MongodbService.java   
private Object updateByFilter(String filter, String update) throws ServiceException {
    try {
        BasicDBObject filterObj = BasicDBObject.parse(filter);
        Document updateObj = new Document(BasicDBObject.parse(update));
        UpdateResult updateResult = this.collection.replaceOne(filterObj, updateObj);

        Map<String, Long> result = new HashMap<String, Long>();
        result.put("matched", updateResult.getMatchedCount());
        result.put("modified", updateResult.getModifiedCount());
        return result;
    } catch (Exception e) {
        throw new ServiceException("Update Exception: " + e.getMessage());
    }
}
项目:pumbaa    文件:MongodbService.java   
private Object updateById(ObjectId idObj, String update) throws ServiceException {
    try {
        Bson filterObj = Filters.eq("_id", idObj);
        Document updateObj = new Document(BasicDBObject.parse(update));
        UpdateResult updateResult = this.collection.replaceOne(filterObj, updateObj);

        Map<String, Long> result = new HashMap<String, Long>();
        result.put("matched", updateResult.getMatchedCount());
        result.put("modified", updateResult.getModifiedCount());
        return result;
    } catch (Exception e) {
        throw new ServiceException("Update Exception: " + e.getMessage());
    }
}
项目:giiwa    文件:MongoHelper.java   
/**
 * inc.
 *
 * @param table
 *            the table
 * @param q
 *            the q
 * @param name
 *            the name
 * @param n
 *            the n
 * @param db
 *            the db
 * @return the int
 */
public int inc(String table, W q, String name, int n, V v, String db) {
    Document d = new Document();

    try {
        d.put(name, n);
        MongoCollection<Document> c = getCollection(db, table);
        Document d2 = new Document("$inc", d);

        Document d1 = null;
        if (v != null) {
            d1 = new Document();
            for (String s : v.names()) {
                Object v1 = v.value(s);
                d1.append(s, v1);
            }
            d2.append("$set", d1);
        }

        UpdateResult r = c.updateMany(q.query(), d2);

        if (log.isDebugEnabled())
            log.debug("updated collection=" + table + ", query=" + q + ", d=" + d + ", n=" + r.getModifiedCount()
                    + ",result=" + r);

        return (int) r.getModifiedCount();
    } catch (Exception e) {
        if (log.isErrorEnabled())
            log.error(e.getMessage(), e);
    }
    return 0;
}
项目:java-toolkit    文件:MongoDriverManager.java   
private UpdateResult baseUpdateOne(String docName, Document doc, Document docFilter) {
    if (doc == null || doc.size() == 0) {
        return null;
    }
    if (docFilter == null) {
        docFilter = new Document();
    }
    MongoCollection<Document> collection = getDBCollection(docName);
    return collection.updateOne(docFilter, new Document(OPERATOR_SET, doc));
}
项目:java-toolkit    文件:MongoDriverManager.java   
private UpdateResult baseUpdateMany(String docName, Document doc, Document docFilter) {
    if (doc == null || doc.size() == 0) {
        return null;
    }
    if (docFilter == null) {
        docFilter = new Document();
    }
    MongoCollection<Document> collection = getDBCollection(docName);
    return collection.updateMany(docFilter, new Document(OPERATOR_SET, doc));
}
项目:java-toolkit    文件:MongoDriverManager.java   
@Override
public boolean updateOne(String docName, Document doc, Document docFilter) {
    UpdateResult upResult = baseUpdateOne(docName, doc, docFilter);
    if (upResult == null) {
        return false;
    }
    long matched = upResult.getMatchedCount();//匹配上的数据条数
    long modified = upResult.getModifiedCount();//已修改的数据条数
    if (matched == 1 && modified == 1) {
        return true;
    }
    return false;
}
项目:java-toolkit    文件:MongoDriverManager.java   
@Override
public boolean updateMany(String docName, Document doc, Document docFilter) {
    UpdateResult upResult = baseUpdateMany(docName, doc, docFilter);
    if (upResult == null) {
        return false;
    }
    long matched = upResult.getMatchedCount();//匹配上的数据条数
    long modified = upResult.getModifiedCount();//已修改的数据条数
    if (matched > 0 && modified > 0) {
        return true;
    }
    return false;
}