List of usage examples for com.mongodb WriteResult getN
public int getN()
From source file:org.opencb.opencga.catalog.db.mongodb.CatalogMongoDBAdaptor.java
License:Apache License
/** * At the moment it does not clean external references to itself. *///from w ww. j a v a 2 s. c o m @Override public QueryResult<Job> deleteJob(int jobId) throws CatalogDBException { long startTime = startQuery(); Job job = getJob(jobId, null).first(); WriteResult id = jobCollection.remove(new BasicDBObject(_ID, jobId), null).getResult().get(0); List<Integer> deletes = new LinkedList<>(); if (id.getN() == 0) { throw CatalogDBException.idNotFound("Job", jobId); } else { deletes.add(id.getN()); return endQuery("delete job", startTime, Collections.singletonList(job)); } }
From source file:org.slc.sli.dal.repository.MongoRepository.java
License:Apache License
@Override public boolean patch(String type, String collectionName, String id, Map<String, Object> newValues) { if (id.equals("")) { return false; }/*from w w w . j av a 2 s . com*/ // prepare to find desired record to be patched Query query = new Query(); query.addCriteria(Criteria.where("_id").is(idConverter.toDatabaseId(id))); query.addCriteria(createTenantCriteria(collectionName)); // prepare update operation for record to be patched Update update = new Update(); for (Entry<String, Object> patch : newValues.entrySet()) { update.set("body." + patch.getKey(), patch.getValue()); } WriteResult result = updateFirst(query, update, collectionName); return (result.getN() == 1); }
From source file:org.socialhistoryservices.pid.database.dao.HandleDaoImpl.java
License:Open Source License
private void upsertHandle(String na, String pid, List<Handle> handles, int action) throws HandleException { // if the handle already exists, throw an exception final BasicDBObject query = new BasicDBObject("handle", pid); final List<HandleValue> currentValues = handleStorage.getHandleValues(pid); if (action == 2 && currentValues.size() == 0) { throw new HandleException(HandleException.HANDLE_DOES_NOT_EXIST, "The pid " + pid + " does not exist. Use the create method."); } else if (action == 1 && currentValues.size() != 0) { throw new HandleException(HandleException.HANDLE_ALREADY_EXISTS, "The pid " + pid + " already exists. Use the update method."); }//ww w . j a v a 2 s . co m // add non-PID webservice handles ( other than those managed here like URL, LID and the 10320/loc ) preserveHandles(na, pid, currentValues, handles); final int timestamp = (int) (System.currentTimeMillis() / 1000); final BasicDBList _lookup = new BasicDBList(); final BasicDBList list = new BasicDBList(); for (Handle handle : handles) { handle.setTimestamp(timestamp); handle.setTTLType(HandleValue.TTL_TYPE_RELATIVE); handle.setTTL(86400); final BasicDBObject hv = handleStorage.setHandleValue(handle); list.add(hv); _lookup.addAll(handle.getLocations()); } final BasicDBObject handle = new BasicDBObject("handle", pid); handle.put("handles", list); handle.put("_lookup", _lookup); final DBCollection collection = handleStorage.getCollection(Util.encodeString(pid)); final WriteResult result = collection.update(query, handle, true, false); // Upsert if (result.getN() == 0) throw new HandleException(900, "Cannot create or update the pid " + pid); }
From source file:org.socialhistoryservices.security.MongoUserDetailService.java
License:Open Source License
public void createUser(MongoUserDetails user) { if (user.getPassword() != null) user.setPassword(HashPassword.encrypt(HASH, user.getPassword())); final DBCollection coll = coll(); BasicDBObject query = new BasicDBObject("username", user.getUsername()); DBObject tmp = coll.findOne(query);// w w w .jav a 2s .c o m if (tmp != null) { if (user.getPassword() == null) { user.setPassword((String) tmp.get("password")); } if (user.getAuthorities().size() == 0) { BasicDBList authorities = (BasicDBList) tmp.get("authorities"); for (Object authority : authorities) { user.getAuthorities() .add(new org.socialhistoryservices.security.MongoAuthority((String) authority)); } } } BasicDBObject document = new BasicDBObject(); document.put("username", user.getUsername()); document.put("password", user.getPassword()); document.put("enabled", user.isEnabled()); document.put("accountNonExpired", user.isAccountNonExpired()); document.put("accountNonLocked", user.isAccountNonLocked()); document.put("credentialsNonExpired", user.isCredentialsNonExpired()); BasicDBList authorities = new BasicDBList(); for (GrantedAuthority authority : user.getAuthorities()) { authorities.add(authority.getAuthority()); } document.put("authorities", authorities); final WriteResult result = coll.update(query, document, true, false, WriteConcern.SAFE); if (result.getN() == 0) log.error(new Exception("Adding the user failed: " + result.getError())); log.info("Persisted:\n" + document.toString()); }
From source file:org.socialhistoryservices.security.MongoUserDetailService.java
License:Open Source License
public boolean remove(String username) { final DBCollection coll = coll(); final BasicDBObject query = new BasicDBObject("username", username); WriteResult result = coll.remove(query, WriteConcern.SAFE); return (result.getN() != 0); }
From source file:org.springframework.data.document.mongodb.MongoTemplate.java
License:Apache License
/** * Checks and handles any errors.//from w ww. ja va 2 s .c om * <p/> * TODO: current implementation logs errors - will be configurable to log warning, errors or * throw exception in later versions */ private void handleAnyWriteResultErrors(WriteResult wr, DBObject query, String operation) { if (WriteResultChecking.NONE == this.writeResultChecking) { return; } String error = wr.getError(); int n = wr.getN(); if (error != null) { String message = "Execution of '" + operation + (query == null ? "" : "' using '" + query.toString() + "' query") + " failed: " + error; if (WriteResultChecking.EXCEPTION == this.writeResultChecking) { throw new DataIntegrityViolationException(message); } else { LOGGER.error(message); } } else if (n == 0) { String message = "Execution of '" + operation + (query == null ? "" : "' using '" + query.toString() + "' query") + " did not succeed: 0 documents updated"; if (WriteResultChecking.EXCEPTION == this.writeResultChecking) { throw new DataIntegrityViolationException(message); } else { LOGGER.warn(message); } } }
From source file:org.springframework.data.mongodb.core.MongoTemplate.java
License:Apache License
protected WriteResult doUpdate(final String collectionName, final Query query, final Update update, final Class<?> entityClass, final boolean upsert, final boolean multi) { return execute(collectionName, new CollectionCallback<WriteResult>() { public WriteResult doInCollection(DBCollection collection) throws MongoException, DataAccessException { MongoPersistentEntity<?> entity = entityClass == null ? null : getPersistentEntity(entityClass); increaseVersionForUpdateIfNecessary(entity, update); DBObject queryObj = query == null ? new BasicDBObject() : queryMapper.getMappedObject(query.getQueryObject(), entity); DBObject updateObj = update == null ? new BasicDBObject() : updateMapper.getMappedObject(update.getUpdateObject(), entity); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Calling update using query: {} and update: {} in collection: {}", serializeToJsonSafely(queryObj), serializeToJsonSafely(updateObj), collectionName); }/* w w w. ja v a2 s. co m*/ MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName, entityClass, updateObj, queryObj); WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction); WriteResult writeResult = writeConcernToUse == null ? collection.update(queryObj, updateObj, upsert, multi) : collection.update(queryObj, updateObj, upsert, multi, writeConcernToUse); if (entity != null && entity.hasVersionProperty() && !multi) { if (ReflectiveWriteResultInvoker.wasAcknowledged(writeResult) && writeResult.getN() == 0 && dbObjectContainsVersionProperty(queryObj, entity)) { throw new OptimisticLockingFailureException("Optimistic lock exception on saving entity: " + updateObj.toMap().toString() + " to collection " + collectionName); } } handleAnyWriteResultErrors(writeResult, queryObj, MongoActionOperation.UPDATE); return writeResult; } }); }
From source file:org.teiid.translator.mongodb.MongoDBUpdateExecution.java
License:Open Source License
private void executeInternal() throws TranslatorException { DBCollection collection = getCollection(this.visitor.mongoDoc.getTargetTable()); MongoDocument mongoDoc = this.visitor.mongoDoc; AggregationOptions options = this.executionFactory.getOptions(this.executionContext.getBatchSize()); List<WriteResult> executionResults = new ArrayList<WriteResult>(); if (this.command instanceof Insert) { // get pull key based documents to embed LinkedHashMap<String, DBObject> embeddedDocuments = fetchEmbeddedDocuments(); // check if this document need to be embedded in any other document if (mongoDoc.isMerged()) { DBObject match = getInsertMatch(mongoDoc, this.visitor.columnValues); BasicDBObject insert = this.visitor.getInsert(embeddedDocuments); if (mongoDoc.getMergeKey().getAssociation() == Association.MANY) { removeParentKey(mongoDoc, insert); BasicDBObject insertDoc = new BasicDBObject(mongoDoc.getQualifiedName(true), insert); LogManager.logDetail(LogConstants.CTX_CONNECTOR, "update - {\"$match\": {" + match + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "update - {\"$push\": {" + insertDoc + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ executionResults.add(collection.update(match, new BasicDBObject("$push", insertDoc), false, //$NON-NLS-1$ true, WriteConcern.ACKNOWLEDGED)); } else { insert.remove("_id"); //$NON-NLS-1$ BasicDBObject insertDoc = new BasicDBObject(mongoDoc.getQualifiedName(true), insert); LogManager.logDetail(LogConstants.CTX_CONNECTOR, "update - {\"$match\": {" + match + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "update - {\"$set\": {" + insertDoc + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ executionResults.add(collection.update(match, new BasicDBObject("$set", insertDoc), false, true, //$NON-NLS-1$ WriteConcern.ACKNOWLEDGED)); }//w w w . ja va2s . co m } else { for (String docName : embeddedDocuments.keySet()) { DBObject embeddedDoc = embeddedDocuments.get(docName); embeddedDoc.removeField("_id"); //$NON-NLS-1$ } // gets its own collection BasicDBObject in = this.visitor.getInsert(embeddedDocuments); LogManager.logDetail(LogConstants.CTX_CONNECTOR, "{\"insert\": {" + in + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ executionResults.add(collection.insert(in, WriteConcern.ACKNOWLEDGED)); } } else if (this.command instanceof Update) { // get pull key based documents to embed LinkedHashMap<String, DBObject> embeddedDocuments = fetchEmbeddedDocuments(); DBObject match = new BasicDBObject(); if (this.visitor.match != null) { match = this.visitor.match; } if (mongoDoc.isMerged()) { // multi items in array update not available, http://jira.mongodb.org/browse/SERVER-1243 // this work-around for above issue List<String> parentKeyNames = parentKeyNames(mongoDoc); DBObject documentMatch = new BasicDBObject("$match", match); //$NON-NLS-1$ DBObject projection = new BasicDBObject("$project", buildProjectForUpdate(mongoDoc)); //$NON-NLS-1$ Cursor output = collection.aggregate(Arrays.asList(documentMatch, projection), options); while (output.hasNext()) { BasicDBObject row = (BasicDBObject) output.next(); buildUpdate(mongoDoc, collection, row, parentKeyNames, 0, null, executionResults, new UpdateOperationImpl()); } } else { for (String docName : embeddedDocuments.keySet()) { DBObject embeddedDoc = embeddedDocuments.get(docName); embeddedDoc.removeField("_id"); //$NON-NLS-1$ } BasicDBObject u = this.visitor.getUpdate(embeddedDocuments); LogManager.logDetail(LogConstants.CTX_CONNECTOR, "update - {\"$match\": {" + match + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "update - {\"$set\": {" + u + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ executionResults.add(collection.update(match, new BasicDBObject("$set", u), false, true, //$NON-NLS-1$ WriteConcern.ACKNOWLEDGED)); } // if the update is for the "embeddable" table, then since it is copied to other tables // those references need to be updated. I know this is not atomic operation, but not sure // how else to handle it. if (mongoDoc.isEmbeddable()) { updateReferenceTables(collection, mongoDoc, match, options); } } else { // Delete DBObject match = new BasicDBObject(); if (this.visitor.match != null) { match = this.visitor.match; } if (mongoDoc.isEmbeddable()) { DBObject m = new BasicDBObject("$match", match); //$NON-NLS-1$ Cursor output = collection.aggregate(Arrays.asList(m), options); while (output.hasNext()) { DBObject row = output.next(); if (row != null) { for (MergeDetails ref : mongoDoc.getEmbeddedIntoReferences()) { DBCollection parent = getCollection(ref.getParentTable()); DBObject parentMatch = buildParentMatch(row, ref); DBObject refMatch = new BasicDBObject("$match", parentMatch); //$NON-NLS-1$ Cursor referenceOutput = parent.aggregate(Arrays.asList(refMatch), options); if (referenceOutput.hasNext()) { throw new TranslatorException(MongoDBPlugin.Util.gs(MongoDBPlugin.Event.TEIID18010, this.visitor.mongoDoc.getTargetTable().getName(), ref.getParentTable())); } } } } } if (mongoDoc.isMerged()) { List<String> parentKeyNames = parentKeyNames(mongoDoc); DBObject documentMatch = new BasicDBObject("$match", match); //$NON-NLS-1$ DBObject projection = new BasicDBObject("$project", buildProjectForUpdate(mongoDoc)); //$NON-NLS-1$ Cursor output = collection.aggregate(Arrays.asList(documentMatch, projection), options); while (output.hasNext()) { BasicDBObject row = (BasicDBObject) output.next(); buildUpdate(mongoDoc, collection, row, parentKeyNames, 0, null, executionResults, new DeleteOperationImpl(match)); } } else { LogManager.logDetail(LogConstants.CTX_CONNECTOR, "remove - {\"$match\": {" + match + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ executionResults.add(collection.remove(match, WriteConcern.ACKNOWLEDGED)); } } if (!executionResults.isEmpty()) { if (this.command instanceof Insert) { if (this.executionContext.getCommandContext().isReturnAutoGeneratedKeys()) { addAutoGeneretedKeys(executionResults.get(0)); } } int updated = 0; for (WriteResult result : executionResults) { updated += result.getN(); } this.results = new int[1]; this.results[0] = updated; } }
From source file:org.trustedanalytics.modelcatalog.storage.db.MongoModelStore.java
License:Apache License
private void verifyWriteResult(WriteResult writeResult, String message) throws ModelStoreException { if (writeResult.getN() <= 0) { throw new ModelStoreException(message); }/*from w ww .ja v a2 s . c om*/ }
From source file:org.vertx.java.busmods.persistor.MongoPersistor.java
License:Apache License
private void doDelete(Message<JsonObject> message) { String collection = getMandatoryString("collection", message); if (collection == null) { return;/* www . ja v a 2 s .co m*/ } JsonObject matcher = getMandatoryObject("matcher", message); if (matcher == null) { return; } DBCollection coll = db.getCollection(collection); DBObject obj = jsonToDBObject(matcher); WriteResult res = coll.remove(obj); int deleted = res.getN(); JsonObject reply = new JsonObject().putNumber("number", deleted); sendOK(message, reply); }