List of usage examples for com.mongodb WriteResult getN
public int getN()
From source file:org.apache.chemistry.opencmis.mongodb.MongodbUtils.java
License:Apache License
public void removeNode(BasicDBObject node) { // Update all affected right and left values which are greater or equal // to the parents right value - we are incrementing to compress the void // left by the removal of the node db.getCollection(COLLECTION_CONTENT).update( new BasicDBObject().append("right", new BasicDBObject().append("$gt", node.getLong("right"))), new BasicDBObject().append("$inc", new BasicDBObject().append("right", -2)), false, true); db.getCollection(COLLECTION_CONTENT).update( new BasicDBObject().append("left", new BasicDBObject().append("$gt", node.getLong("right"))), new BasicDBObject().append("$inc", new BasicDBObject().append("left", -2)), false, true); // Finally remove the node WriteResult result = db.getCollection(COLLECTION_CONTENT).remove(node); if (result.getN() != 1) { throw new MongoException("Error while removing the node from the database."); }/*from w ww. j a v a 2 s .c o m*/ }
From source file:org.apache.drill.exec.store.mongo.config.MongoPStore.java
License:Apache License
@Override public boolean putIfAbsent(String key, V value) { try {//from w ww.ja v a2 s.c o m DBObject check = new BasicDBObject(1).append(ID, key); DBObject putObj = new BasicDBObject(2); putObj.put(pKey, bytes(value)); WriteResult wr = collection.update(check, putObj, true, false); return wr.getN() == 1 ? true : false; } catch (Exception e) { logger.error(e.getMessage(), e); throw new DrillRuntimeException(e.getMessage(), e); } }
From source file:org.apache.gora.mongodb.store.MongoStore.java
License:Apache License
@Override public boolean delete(final K key) { DBObject removeKey = new BasicDBObject("_id", key); WriteResult writeResult = mongoClientColl.remove(removeKey); return writeResult != null && writeResult.getN() > 0; }
From source file:org.apache.gora.mongodb.store.MongoStore.java
License:Apache License
@Override public long deleteByQuery(final Query<K, T> query) { // Build the actual MongoDB query DBObject q = MongoDBQuery.toDBQuery(query); WriteResult writeResult = mongoClientColl.remove(q); if (writeResult != null) { return writeResult.getN(); }/*from www .j a v a 2s . c om*/ return 0; }
From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoBlobStore.java
License:Apache License
@Override public long countDeleteChunks(List<String> chunkIds, long maxLastModifiedTime) throws Exception { DBCollection collection = getBlobCollection(); QueryBuilder queryBuilder = new QueryBuilder(); if (chunkIds != null) { queryBuilder = queryBuilder.and(MongoBlob.KEY_ID).in(chunkIds.toArray(new String[0])); if (maxLastModifiedTime > 0) { queryBuilder = queryBuilder.and(MongoBlob.KEY_LAST_MOD).lessThan(maxLastModifiedTime); }// www . j a v a 2 s .com } WriteResult result = collection.remove(queryBuilder.get()); return result.getN(); }
From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore.java
License:Apache License
@SuppressWarnings("unchecked") @CheckForNull// w w w. j a v a 2 s . c o m private <T extends Document> T findAndModify(Collection<T> collection, UpdateOp updateOp, boolean upsert, boolean checkConditions) { DBCollection dbCollection = getDBCollection(collection); // make sure we don't modify the original updateOp updateOp = updateOp.copy(); DBObject update = createUpdate(updateOp, false); Lock lock = null; if (collection == Collection.NODES) { lock = nodeLocks.acquire(updateOp.getId()); } final Stopwatch watch = startWatch(); boolean newEntry = false; try { // get modCount of cached document Long modCount = null; T cachedDoc = null; if (collection == Collection.NODES) { cachedDoc = (T) nodesCache.getIfPresent(updateOp.getId()); if (cachedDoc != null) { modCount = cachedDoc.getModCount(); } } // perform a conditional update with limited result // if we have a matching modCount if (modCount != null) { QueryBuilder query = createQueryForUpdate(updateOp.getId(), updateOp.getConditions()); query.and(Document.MOD_COUNT).is(modCount); WriteResult result = dbCollection.update(query.get(), update); if (result.getN() > 0) { // success, update cached document if (collection == Collection.NODES) { NodeDocument newDoc = (NodeDocument) applyChanges(collection, cachedDoc, updateOp); nodesCache.put(newDoc); } // return previously cached document return cachedDoc; } } // conditional update failed or not possible // perform operation and get complete document QueryBuilder query = createQueryForUpdate(updateOp.getId(), updateOp.getConditions()); DBObject oldNode = dbCollection.findAndModify(query.get(), null, null /*sort*/, false /*remove*/, update, false /*returnNew*/, upsert); if (oldNode == null) { newEntry = true; } if (checkConditions && oldNode == null) { return null; } T oldDoc = convertFromDBObject(collection, oldNode); if (oldDoc != null) { if (collection == Collection.NODES) { NodeDocument newDoc = (NodeDocument) applyChanges(collection, oldDoc, updateOp); nodesCache.put(newDoc); updateLocalChanges(newDoc); } oldDoc.seal(); } else if (upsert) { if (collection == Collection.NODES) { NodeDocument doc = (NodeDocument) collection.newDocument(this); UpdateUtils.applyChanges(doc, updateOp); nodesCache.putIfAbsent(doc); updateLocalChanges(doc); } } else { // updateOp without conditions and not an upsert // this means the document does not exist } return oldDoc; } catch (Exception e) { throw DocumentStoreException.convert(e); } finally { if (lock != null) { lock.unlock(); } stats.doneFindAndModify(watch.elapsed(TimeUnit.NANOSECONDS), collection, updateOp.getId(), newEntry, true, 0); } }
From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStoreHelper.java
License:Apache License
public static void repair(MongoDocumentStore store, String path) { DBCollection col = store.getDBCollection(NODES); String id = Utils.getIdFromPath(path); NodeDocument doc = store.find(NODES, id); if (doc == null) { System.out.println("No document for path " + path); return;//from w w w . ja va 2s . c o m } Set<Revision> changes = Sets.newHashSet(); for (String key : doc.keySet()) { if (Utils.isPropertyName(key) || NodeDocument.isDeletedEntry(key)) { changes.addAll(getLocalMap(doc, key).keySet()); } } SortedMap<Revision, String> commitRoot = newTreeMap(getLocalCommitRoot(doc)); if (!commitRoot.keySet().retainAll(changes)) { System.out.println("Nothing to repair on " + path); return; } Number modCount = doc.getModCount(); if (modCount == null) { System.err.println("Document does not have a modCount " + path); return; } DBObject query = QueryBuilder.start(Document.ID).is(id).and(Document.MOD_COUNT).is(modCount).get(); DBObject cr = new BasicDBObject(); for (Map.Entry<Revision, String> entry : commitRoot.entrySet()) { cr.put(entry.getKey().toString(), entry.getValue()); } DBObject update = new BasicDBObject(); update.put("$set", new BasicDBObject(commitRoot(), cr)); update.put("$inc", new BasicDBObject(Document.MOD_COUNT, 1L)); WriteResult result = col.update(query, update); if (result.getN() == 1) { int num = getLocalCommitRoot(doc).size() - commitRoot.size(); System.out.println("Removed " + num + " _commitRoot entries on " + path); } else { System.out.println("Unable to repair " + path + " (concurrent update)."); } }
From source file:org.apache.nutch.crawl.GeneratorJob2.java
License:Apache License
public int generateBatchId(Configuration conf, String batchId) { MongoClient mongoClient = null;/*from w w w . j av a 2 s . co m*/ try { mongoClient = new MongoClient(goraMongoAddress); DB db = mongoClient.getDB(goraMongoDb); String cId = conf.get(Nutch.CRAWL_ID_KEY); String collPrefix = ""; if (org.apache.commons.lang3.StringUtils.isNoneEmpty(cId)) { collPrefix = cId + "_"; } String crawlColl = collPrefix + "webpage"; DBCollection collOps = db.getCollection(crawlColl); //update({"count":{$gt:20}},{$set:{"name":"c4"}},false,true) BasicDBObject q = new BasicDBObject("batchId", null); DBObject set = new BasicDBObject("batchId", batchId); set.put("markers._gnmrk_", batchId); BasicDBObject o = new BasicDBObject("$set", set); WriteResult wr = collOps.update(q, o, false, true); long curTime = System.currentTimeMillis(); //taotoxht add q = new BasicDBObject(); q.append("fetchTime", new BasicDBObject().append(QueryOperators.GT, curTime)); o = new BasicDBObject(); o.append("$set", new BasicDBObject().append("fetchTime", curTime)); collOps.update(q, o, false, true); return wr.getN(); } catch (Exception e) { e.printStackTrace(); return 0; } finally { if (mongoClient != null) { mongoClient.close(); } } }
From source file:org.apache.rave.portal.repository.impl.MongoModelTemplate.java
License:Apache License
@Override public int update(Query query, Update update) { WriteResult result = mongoTemplate.updateMulti(query, update, collection); return result.getN(); }
From source file:org.apache.rya.mongodb.instance.MongoRyaInstanceDetailsRepository.java
License:Apache License
@Override public void update(final RyaDetails oldDetails, final RyaDetails newDetails) throws NotInitializedException, ConcurrentUpdateException, RyaDetailsRepositoryException { // Preconditions. requireNonNull(oldDetails);/*from w ww . j a v a 2 s. c o m*/ requireNonNull(newDetails); if (!newDetails.getRyaInstanceName().equals(instanceName)) { throw new RyaDetailsRepositoryException( "The instance name that was in the provided 'newDetails' does not match " + "the instance name that this repository is connected to. Make sure you're connected to the" + "correct Rya instance."); } if (!isInitialized()) { throw new NotInitializedException("Could not update the details for the Rya instanced named '" + instanceName + "' because it has not been initialized yet."); } if (oldDetails.equals(newDetails)) { return; } final DBCollection col = db.getCollection(INSTANCE_DETAILS_COLLECTION_NAME); final DBObject oldObj = MongoDetailsAdapter.toDBObject(oldDetails); final DBObject newObj = MongoDetailsAdapter.toDBObject(newDetails); final WriteResult result = col.update(oldObj, newObj); //since there is only 1 document, there should only be 1 update. if (result.getN() != 1) { throw new ConcurrentUpdateException("Could not update the details for the Rya instance named '" + instanceName + "' because the old value is out of date."); } }