Пример #1
0
  public int update() throws Exception {
    if (optimistic) {
      where.put("__version", store.mcnv.toMongo(store.versions.get(optimisticDocument)));
    }
    inc("__version", 1);

    WriteResult result = store.collection.update(where, update, false, !optimistic);
    store.error(result);
    if (optimistic && result.getN() == 0) {
      throw new ConcurrentModificationException("Document was modified after obtention");
    }
    return result.getN();
  }
Пример #2
0
  @Override
  public void update(KeycloakSession session) {
    BasicDBList orArgs = new BasicDBList();
    orArgs.add(new BasicDBObject("type", UserCredentialModel.PASSWORD));
    orArgs.add(new BasicDBObject("type", UserCredentialModel.PASSWORD_HISTORY));

    BasicDBObject elemMatch = new BasicDBObject("$or", orArgs);
    elemMatch.put("algorithm", new BasicDBObject("$exists", false));

    BasicDBObject query =
        new BasicDBObject("credentials", new BasicDBObject("$elemMatch", elemMatch));

    BasicDBObject update =
        new BasicDBObject(
            "$set", new BasicDBObject("credentials.$.algorithm", Pbkdf2PasswordHashProvider.ID));

    DBCollection users = db.getCollection("users");

    // Not sure how to do in single query
    int countModified = 1;
    while (countModified > 0) {
      WriteResult wr = users.update(query, update, false, true);
      countModified = wr.getN();
      log.debugf(
          "%d credentials modified in current iteration during upgrade to 1.8", countModified);
    }
  }
  @Test
  public void testUsingUpdateWithMultipleSet() throws Exception {

    template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class);

    PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId();
    p1.setFirstName("Sven");
    p1.setAge(11);
    template.insert(p1);
    PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId();
    p2.setFirstName("Mary");
    p2.setAge(21);
    template.insert(p2);

    Update u = new Update().set("firstName", "Bob").set("age", 10);

    WriteResult wr = template.updateMulti(new Query(), u, PersonWithIdPropertyOfTypeObjectId.class);

    assertThat(wr.getN(), is(2));

    Query q1 = new Query(Criteria.where("age").in(11, 21));
    List<PersonWithIdPropertyOfTypeObjectId> r1 =
        template.find(q1, PersonWithIdPropertyOfTypeObjectId.class);
    assertThat(r1.size(), is(0));
    Query q2 = new Query(Criteria.where("age").is(10));
    List<PersonWithIdPropertyOfTypeObjectId> r2 =
        template.find(q2, PersonWithIdPropertyOfTypeObjectId.class);
    assertThat(r2.size(), is(2));
    for (PersonWithIdPropertyOfTypeObjectId p : r2) {
      assertThat(p.getAge(), is(10));
      assertThat(p.getFirstName(), is("Bob"));
    }
  }
Пример #4
0
  public static void main(String[] args) throws UnknownHostException {

    MongoClient client = new MongoClient();
    DB database = client.getDB("school");
    DBCollection collection = database.getCollection("students");
    /*
     Hint/spoiler: With the new schema, this problem is a lot harder
     and that is sort of the point. One way is to find the lowest
     homework in code and then update the scores array with the low
     homework pruned. If you are struggling with the Node.js side of
     this, look at the .slice() operator, which can remove an element
     from an array in-place.
    */
    DBCursor cursor = collection.find();

    try {
      while (cursor.hasNext()) {
        BasicDBObject student = (BasicDBObject) cursor.next();

        int studentId = student.getInt("_id");
        String name = student.getString("name");
        BasicDBList scores = (BasicDBList) student.get("scores");
        System.out.printf("_id[%d], name[%s], scores%s %n", studentId, name, scores);

        DBObject scoreToRemove = null;
        double minScoreValue = 100.0;

        for (Object obj : scores) {
          BasicDBObject score = (BasicDBObject) obj;
          String type = score.getString("type");

          if (!"homework".equals(type)) {
            continue;
          }
          double curScoreValue = score.getDouble("score");
          System.out.printf("type[%s], current score value[%f] %n", type, curScoreValue);

          if (curScoreValue < minScoreValue) {
            scoreToRemove = score;
            minScoreValue = curScoreValue;
          }
        }
        System.out.printf("score to remove[%s] %n", scoreToRemove);

        if (scoreToRemove != null) {
          scores.remove(scoreToRemove);

          BasicDBObject query = new BasicDBObject("_id", studentId);
          BasicDBObject scoresUpdate =
              new BasicDBObject("$set", new BasicDBObject("scores", scores));
          WriteResult result = collection.update(query, scoresUpdate);
          System.out.printf("update count[%d] %n", result.getN());
        }
      }
    } finally {
      cursor.close();
    }
  }
Пример #5
0
 @Override
 public int updateActualUserReference(String id, Reference newRef) {
   Query q = new Query();
   q.addCriteria(Criteria.where("id").is(id));
   Update u = new Update();
   u.set("actualUser", newRef);
   WriteResult w = mongoOp.updateFirst(q, u, Character.class);
   return w.getN();
 }
Пример #6
0
  @Test
  public void testSetState() throws Exception {
    WriteResult response = mock(WriteResult.class);
    when(response.getN()).thenReturn(1);
    when(missedCalls.update(any(DBObject.class), any(DBObject.class))).thenReturn(response);

    assertTrue(missedCallsDAO.setState(new BasicDBObject("state", "Processing"), "Bogus"));
    verify(missedCalls, times(1)).update(any(DBObject.class), any(DBObject.class));
  }
Пример #7
0
 @Test
 public void testUpdateWithObjectIdReturnModifiedDocumentCount() {
   DBCollection collection = newCollection();
   collection.insert(new BasicDBObject("_id", new BasicDBObject("n", 1)));
   DBObject query = new BasicDBObject("_id", new BasicDBObject("n", 1));
   DBObject update = new BasicDBObject("$set", new BasicDBObject("a", 1));
   WriteResult result = collection.update(query, update, false, false);
   assertEquals(1, result.getN());
 }
Пример #8
0
  @SuppressWarnings("unchecked")
  protected void doUpdate(Exchange exchange) throws Exception {
    DBCollection dbCol = calculateCollection(exchange);
    List<DBObject> saveObj =
        exchange.getIn().getMandatoryBody((Class<List<DBObject>>) (Class<?>) List.class);
    if (saveObj.size() != 2) {
      throw new CamelMongoDbException(
          "MongoDB operation = insert, failed because body is not a List of DBObject objects with size = 2");
    }

    DBObject updateCriteria = saveObj.get(0);
    DBObject objNew = saveObj.get(1);

    Boolean multi = exchange.getIn().getHeader(MongoDbConstants.MULTIUPDATE, Boolean.class);
    Boolean upsert = exchange.getIn().getHeader(MongoDbConstants.UPSERT, Boolean.class);

    WriteResult result;
    WriteConcern wc = extractWriteConcern(exchange);
    // In API 2.7, the default upsert and multi values of update(DBObject, DBObject) are false,
    // false, so we unconditionally invoke the
    // full-signature method update(DBObject, DBObject, boolean, boolean). However, the default
    // behaviour may change in the future,
    // so it's safer to be explicit at this level for full determinism
    if (multi == null && upsert == null) {
      // for update with no multi nor upsert but with specific WriteConcern there is no update
      // signature without multi and upsert args,
      // so assume defaults
      result =
          wc == null
              ? dbCol.update(updateCriteria, objNew)
              : dbCol.update(updateCriteria, objNew, false, false, wc);
    } else {
      // we calculate the final boolean values so that if any of these
      // parameters is null, it is resolved to false
      result =
          wc == null
              ? dbCol.update(
                  updateCriteria,
                  objNew,
                  calculateBooleanValue(upsert),
                  calculateBooleanValue(multi))
              : dbCol.update(
                  updateCriteria,
                  objNew,
                  calculateBooleanValue(upsert),
                  calculateBooleanValue(multi),
                  wc);
    }

    Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.update);
    // we always return the WriteResult, because whether the getLastError was called or not, the
    // user will have the means to call it or
    // obtain the cached CommandResult
    processAndTransferWriteResult(result, exchange);
    resultMessage.setHeader(MongoDbConstants.RECORDS_AFFECTED, result.getN());
  }
 /** Delete a {<span class="referer">@link</span> Task} for a particular id. */
 public boolean deleteObjectById(String id) {
   WriteResult result = mongoTemplate.remove(new Query(Criteria.where("uid").is(id)), Task.class);
   result.getLastError();
   if (null != result) {
     if (result.getN() > 0) {
       return true;
     }
   }
   return false;
 }
 @Override
 public boolean deleteObject(Task object) {
   WriteResult result = mongoTemplate.remove(object);
   result.getLastError();
   if (null != result) {
     if (result.getN() > 0) {
       return true;
     }
   }
   return false;
 }
Пример #11
0
 @Test
 public void testUpdateWithIdInMultiReturnModifiedDocumentCount() {
   DBCollection collection = newCollection();
   collection.insert(new BasicDBObject("_id", 1), new BasicDBObject("_id", 2));
   WriteResult result =
       collection.update(
           new BasicDBObject("_id", new BasicDBObject("$in", Arrays.asList(1, 2))),
           new BasicDBObject("$set", new BasicDBObject("n", 1)),
           false,
           true);
   assertEquals(2, result.getN());
 }
Пример #12
0
  protected void doRemove(Exchange exchange) throws Exception {
    DBCollection dbCol = calculateCollection(exchange);
    DBObject removeObj = exchange.getIn().getMandatoryBody(DBObject.class);

    WriteConcern wc = extractWriteConcern(exchange);
    WriteResult result = wc == null ? dbCol.remove(removeObj) : dbCol.remove(removeObj, wc);

    Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.remove);
    // we always return the WriteResult, because whether the getLastError was called or not,
    // the user will have the means to call it or obtain the cached CommandResult
    processAndTransferWriteResult(result, exchange);
    resultMessage.setHeader(MongoDbConstants.RECORDS_AFFECTED, result.getN());
  }
 @Override
 public boolean saveEmailTemplate(final String context, final String type, final String template)
     throws SocialException {
   try {
     String findQ = getQueryFor("social.system.preferences.byContextAndTemplateType");
     String updateQ = getQueryFor("social.system.preferences.updateContextTemplateType");
     final WriteResult r =
         getCollection().update(findQ, context, type.toUpperCase()).with(updateQ, template);
     checkCommandResult(r);
     return r.getN() == 1;
   } catch (MongoException | MongoDataException ex) {
     throw new SocialException("Unable to update Email template", ex);
   }
 }
 /** 更新数据库下载状态 一般用于数据库初始化* */
 @Override
 public void updateDownloadComplete(YandeCG yandeCG) {
   DBObject mongoYandeCG = new BasicDBObject();
   mongoYandeCG.put("_id", yandeCG.getMd5());
   DBObject mongoYandeCGNew = new BasicDBObject();
   mongoYandeCGNew.put("_id", yandeCG.getMd5());
   mongoYandeCGNew.put("id", yandeCG.getId());
   mongoYandeCGNew.put("md5", yandeCG.getMd5());
   mongoYandeCGNew.put("downComplete", yandeCG.isDownComplete());
   mongoYandeCGNew.put("tags", yandeCG.getTags());
   mongoYandeCGNew.put("source", yandeCG.getSource());
   mongoYandeCGNew.put("file_url", yandeCG.getFile_url());
   mongoYandeCGNew.put("file_size", yandeCG.getFile_size());
   WriteResult num = collection.update(mongoYandeCG, mongoYandeCGNew);
   logger.info("完成更新YandeCG下载状态 受影响的行数: " + num.getN());
 }
  @Override
  public List<Role2> addAll(List<Role2> upRoleList) {
    final List<DBObject> dbObjects =
        upRoleList
            .stream()
            .map(
                new java.util.function.Function<Role2, DBObject>() {
                  @Override
                  public DBObject apply(Role2 t) {
                    return new EntityToDBObject().apply(t);
                  }
                })
            .collect(Collectors.toList());

    final WriteResult result = rolePersonColl.insert(dbObjects);
    log.info("{} role(s) has/have been added", result.getN());

    return upRoleList;
  }
Пример #16
0
 @Override
 public void delete(
     CRUDOperationContext ctx,
     DBCollection collection,
     DBObject mongoQuery,
     CRUDDeleteResponse response) {
   LOGGER.debug("Computing the result set for {}", mongoQuery);
   DBCursor cursor = null;
   int docIndex = 0;
   int numDeleted = 0;
   try {
     // Find docs
     cursor = new FindCommand(collection, mongoQuery, null).execute();
     LOGGER.debug("Found {} documents", cursor.count());
     // read-delet
     while (cursor.hasNext()) {
       DBObject document = cursor.next();
       LOGGER.debug("Retrieved doc {}", docIndex);
       Object id = document.get(MongoCRUDController.ID_STR);
       DocCtx doc = ctx.addDocument(translator.toJson(document));
       doc.setOriginalDocument(doc);
       ctx.getFactory()
           .getInterceptors()
           .callInterceptors(InterceptPoint.PRE_CRUD_DELETE_DOC, ctx, doc);
       WriteResult result =
           new RemoveCommand(collection, new BasicDBObject("_id", id), WriteConcern.SAFE)
               .execute();
       if (result.getN() == 1) {
         numDeleted++;
         doc.setCRUDOperationPerformed(CRUDOperation.DELETE);
       }
       ctx.getFactory()
           .getInterceptors()
           .callInterceptors(InterceptPoint.POST_CRUD_DELETE_DOC, ctx, doc);
       docIndex++;
     }
   } finally {
     if (cursor != null) {
       cursor.close();
     }
   }
   response.setNumDeleted(numDeleted);
 }
 /** Output records are not supported/required. */
 public boolean execute(InteractionSpec spec, Record input, Record output)
     throws ResourceException {
   if (!(spec instanceof MongoInteractionSpec)) {
     throw EISException.invalidInteractionSpecType();
   }
   if (!(input instanceof MongoRecord) || !(output instanceof MongoRecord)) {
     throw EISException.invalidRecordType();
   }
   MongoInteractionSpec mongoSpec = (MongoInteractionSpec) spec;
   MongoRecord record = (MongoRecord) input;
   MongoRecord translationRecord = (MongoRecord) output;
   MongoOperation operation = mongoSpec.getOperation();
   String collectionName = mongoSpec.getCollection();
   if (operation == null) {
     throw new ResourceException("Mongo operation must be set");
   }
   if (collectionName == null) {
     throw new ResourceException("DB Collection name must be set");
   }
   try {
     DBCollection collection = this.connection.getDB().getCollection(collectionName);
     DBObject object = buildDBObject(record);
     DBObject translation = buildDBObject(translationRecord);
     if (operation == MongoOperation.UPDATE) {
       WriteResult result =
           collection.update(translation, object, mongoSpec.isUpsert(), mongoSpec.isMulti());
       return result.getN() > 0;
     } else {
       throw new ResourceException("Invalid operation: " + operation);
     }
   } catch (Exception exception) {
     ResourceException resourceException = new ResourceException(exception.toString());
     resourceException.initCause(exception);
     throw resourceException;
   }
 }
Пример #18
0
 public int remove() {
   WriteResult result = store.collection.remove(where);
   store.error(result);
   return result.getN();
 }
Пример #19
0
 @Test
 public void testInsertReturnModifiedDocumentCount() {
   DBCollection collection = newCollection();
   WriteResult result = collection.insert(new BasicDBObject("_id", new BasicDBObject("n", 1)));
   assertEquals(1, result.getN());
 }