List of usage examples for com.mongodb.client.result UpdateResult getMatchedCount
public abstract long getMatchedCount();
From source file:org.graylog2.migrations.V20170110150100_FixAlertConditionsMigration.java
License:Open Source License
@Override @SuppressWarnings("unchecked") public void upgrade() { if (clusterConfigService.get(MigrationCompleted.class) != null) { LOG.debug("Migration already done."); return;/* w ww. ja v a 2s . co m*/ } final ImmutableSet.Builder<String> modifiedStreams = ImmutableSet.builder(); final ImmutableSet.Builder<String> modifiedAlertConditions = ImmutableSet.builder(); for (Document document : collection.find().sort(ascending(FIELD_CREATED_AT))) { final String streamId = document.getObjectId(FIELD_ID).toHexString(); if (!document.containsKey(FIELD_ALERT_CONDITIONS)) { continue; } final List<Document> alertConditions = (List<Document>) document.get(FIELD_ALERT_CONDITIONS); // Need to check if the following fields are integers: // // FieldContentValue: grace, backlog // FieldValue: grace, backlog, time, threshold // MessageCount: grace, backlog, time, threshold final Set<String> intFields = ImmutableSet.of("grace", "backlog", "time", "threshold"); for (Document alertCondition : alertConditions) { final String alertConditionId = alertCondition.get("id", String.class); final String alertConditionTitle = alertCondition.get("title", String.class); final Document parameters = alertCondition.get("parameters", Document.class); for (String field : intFields) { final Object fieldValue = parameters.get(field); // No need to convert anything if the field does not exist or is already an integer if (fieldValue == null || fieldValue instanceof Integer) { continue; } if (!(fieldValue instanceof String)) { LOG.warn( "Field <{}> in alert condition <{}> ({}) of stream <{}> is not a string but a <{}>, not trying to convert it!", field, alertConditionId, alertConditionTitle, streamId, fieldValue.getClass().getCanonicalName()); continue; } final String stringValue = parameters.get(field, String.class); final Integer intValue = Ints.tryParse(stringValue); LOG.info( "Converting value for field <{}> from string to integer in alert condition <{}> ({}) of stream <{}>", field, alertConditionId, alertConditionTitle, streamId); if (intValue == null) { LOG.error("Unable to parse \"{}\" into integer!", fieldValue); } final UpdateResult result = collection.updateOne( eq(FIELD_ALERT_CONDITIONS_ID, alertConditionId), set(ALERT_CONDITIONS_PARAMETERS_PREFIX + field, intValue)); // Use UpdateResult#getMatchedCount() instead of #getModifiedCount() to make it work on MongoDB 2.4 if (result.getMatchedCount() > 0) { modifiedStreams.add(streamId); modifiedAlertConditions.add(alertConditionId); } else { LOG.warn("No document modified for alert condition <{}> ({})", alertConditionId, alertConditionTitle); } } } } clusterConfigService .write(MigrationCompleted.create(modifiedStreams.build(), modifiedAlertConditions.build())); }
From source file:org.lambdamatic.mongodb.internal.LambdamaticMongoCollectionImpl.java
License:Open Source License
@Override public void replace(final DomainType domainObject) { final BsonDocument idFilterDocument = BsonUtils.asBsonDocument(new IdFilter<>(domainObject)); final UpdateResult result = getMongoCollection().replaceOne(idFilterDocument, domainObject); if (result.isModifiedCountAvailable() && result.getMatchedCount() != 1) { throw new OperationException( "Invalid number of document match during the update operation: " + result.getMatchedCount()); }// w w w. jav a 2 s . co m }
From source file:org.nuxeo.directory.mongodb.MongoDBSession.java
License:Apache License
@Override public void updateEntry(DocumentModel docModel) throws DirectoryException { checkPermission(SecurityConstants.WRITE); Map<String, Object> fieldMap = new HashMap<>(); List<String> referenceFieldList = new LinkedList<>(); for (String fieldName : schemaFieldMap.keySet()) { Property prop = docModel.getPropertyObject(schemaName, fieldName); if (fieldName.equals(getPasswordField()) && StringUtils.isEmpty((String) prop.getValue())) { continue; }//from w w w.j av a 2s .c o m if (prop != null && prop.isDirty()) { Serializable value = prop.getValue(); if (fieldName.equals(getPasswordField())) { value = PasswordHelper.hashPassword((String) value, passwordHashAlgorithm); } fieldMap.put(prop.getName(), value); } if (getDirectory().isReference(fieldName)) { referenceFieldList.add(fieldName); } } String id = docModel.getId(); Document bson = MongoDBSerializationHelper.fieldMapToBson(getIdField(), id); List<Bson> updates = fieldMap.entrySet().stream().map(e -> Updates.set(e.getKey(), e.getValue())) .collect(Collectors.toList()); try { UpdateResult result = getCollection().updateOne(bson, Updates.combine(updates)); // Throw an error if no document matched the update if (!result.wasAcknowledged()) { throw new DirectoryException( "Error while updating the entry, the request has not been acknowledged by the server"); } if (result.getMatchedCount() == 0) { throw new DirectoryException( String.format("Error while updating the entry, no document was found with the id %s", id)); } } catch (MongoWriteException e) { throw new DirectoryException(e); } // update reference fields for (String referenceFieldName : referenceFieldList) { List<Reference> references = directory.getReferences(referenceFieldName); if (references.size() > 1) { // not supported log.warn("Directory " + getDirectory().getName() + " cannot update field " + referenceFieldName + " for entry " + docModel.getId() + ": this field is associated with more than one reference"); } else { Reference reference = references.get(0); @SuppressWarnings("unchecked") List<String> targetIds = (List<String>) docModel.getProperty(schemaName, referenceFieldName); if (reference instanceof MongoDBReference) { MongoDBReference mongoReference = (MongoDBReference) reference; mongoReference.setTargetIdsForSource(docModel.getId(), targetIds, this); } else { reference.setTargetIdsForSource(docModel.getId(), targetIds); } } } getDirectory().invalidateCaches(); }