Java Code Examples for com.mongodb.client.result.DeleteResult#getDeletedCount()

The following examples show how to use com.mongodb.client.result.DeleteResult#getDeletedCount() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MongoSession.java    From presto with Apache License 2.0 6 votes vote down vote up
private boolean deleteTableMetadata(SchemaTableName schemaTableName)
{
    String schemaName = toRemoteSchemaName(schemaTableName.getSchemaName());
    String tableName = toRemoteTableName(schemaName, schemaTableName.getTableName());

    MongoDatabase db = client.getDatabase(schemaName);
    if (!collectionExists(db, tableName) &&
            db.getCollection(schemaCollection).find(new Document(TABLE_NAME_KEY, tableName)).first().isEmpty()) {
        return false;
    }

    DeleteResult result = db.getCollection(schemaCollection)
            .deleteOne(new Document(TABLE_NAME_KEY, tableName));

    return result.getDeletedCount() == 1;
}
 
Example 2
Source File: MongoCompensableLock.java    From ByteTCC with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void unlockTransactionInMongoDB(TransactionXid transactionXid, String identifier) {
	byte[] global = transactionXid.getGlobalTransactionId();
	String instanceId = ByteUtils.byteArrayToString(global);

	try {
		String application = CommonUtils.getApplication(this.endpoint);
		String databaseName = application.replaceAll("\\W", "_");
		MongoDatabase mdb = this.mongoClient.getDatabase(databaseName);
		MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_LOCKS);

		Bson globalFilter = Filters.eq(CONSTANTS_FD_GLOBAL, instanceId);
		Bson instIdFilter = Filters.eq("identifier", identifier);

		DeleteResult result = collection.deleteOne(Filters.and(globalFilter, instIdFilter));
		if (result.getDeletedCount() == 0) {
			logger.warn("Error occurred while unlocking transaction(gxid= {}).", instanceId);
		}
	} catch (RuntimeException rex) {
		logger.error("Error occurred while unlocking transaction(gxid= {})!", instanceId, rex);
	}
}
 
Example 3
Source File: MongodbManager.java    From grain with MIT License 6 votes vote down vote up
/**
 * 删除记录
 * 
 * @param collectionName
 *            表名
 * @param mongoObj
 *            记录
 * @return
 */
public static boolean deleteById(String collectionName, MongoObj mongoObj) {
	MongoCollection<Document> collection = getCollection(collectionName);
	try {
		Bson filter = Filters.eq(MongoConfig.MONGO_ID, mongoObj.getDocument().getObjectId(MongoConfig.MONGO_ID));
		DeleteResult result = collection.deleteOne(filter);
		if (result.getDeletedCount() == 1) {
			return true;
		} else {
			return false;
		}
	} catch (Exception e) {
		if (log != null) {
			log.error("删除记录失败", e);
		}
		return false;
	}

}
 
Example 4
Source File: PersonServiceWithMongo.java    From microshed-testing with Apache License 2.0 5 votes vote down vote up
@DELETE
@Path("/{personId}")
public void removePerson(@PathParam("personId") long id) {
    DeleteResult result = peopleCollection.deleteOne(eq("id", id));
    if (result.getDeletedCount() != 1)
        personNotFound(id);
}
 
Example 5
Source File: MongoCollectionImpl.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
@Override
public boolean delete(Object id) {
    var watch = new StopWatch();
    long deletedRows = 0;
    try {
        DeleteResult result = collection().deleteOne(Filters.eq("_id", id));
        deletedRows = result.getDeletedCount();
        return deletedRows == 1;
    } finally {
        long elapsed = watch.elapsed();
        ActionLogContext.track("mongo", elapsed, 0, (int) deletedRows);
        logger.debug("delete, collection={}, id={}, elapsed={}", collectionName, id, elapsed);
        checkSlowOperation(elapsed);
    }
}
 
Example 6
Source File: ContentInstanceAnncDAO.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private int deleteOldestNExpired(String containerId, int size) {
		
		log.debug("deleteOldestNExpired containerId:{}, size:{}", containerId, size);
		MongoCollection<Document> collection = context.getDatabaseManager()
				.getCollection(collectionName);
		BasicDBList and = new BasicDBList();
		DeleteResult result;
		
		if (size >= 0) {
			and.clear();	
			and.add(new BasicDBObject(PARENTID_KEY, containerId));
			and.add(new BasicDBObject(RESTYPE_KEY, RESOURCE_TYPE.CONTENT_INST.Value()));
			
			MongoCursor<Document> cursor = collection.find(new BasicDBObject("$and", and))
											.sort(new BasicDBObject(CREATETIME_KEY, 1))
											.limit(size).iterator();
			
			int deletedCount = 0;
			if (cursor.hasNext()) {
				Document doc = cursor.next();
//				and.clear();
//				and.add(new BasicDBObject(PARENTID_KEY, containerId));
//				and.add(new BasicDBObject(RESTYPE_KEY, RESOURCE_TYPE.CONTENT_INST.Value()));
//				and.add(new BasicDBObject(CREATETIME_KEY, new BasicDBObject("$lt", doc.get(CREATETIME_KEY))));
//				
				result = collection.deleteOne(new BasicDBObject(RESID_KEY, doc.get(RESID_KEY)));
	
				deletedCount += result.getDeletedCount();
			}
			log.debug("Deleted oldest contentInstance:{}", deletedCount);
			return deletedCount;
		}
		return 0;
		
	}
 
Example 7
Source File: DeleteOperation.java    From mongodb-performance-test with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
long executeQuery(int threadId, long threadRunCount, long globalRunCount, long selectorId, long randomId) {

    final DeleteResult res = THREAD_RUN_COUNT.equals(queriedField)?mongoCollection.deleteMany(eq(queriedField, selectorId))
            :ID.equals(queriedField)?mongoCollection.deleteOne(eq(queriedField, selectorId)):null;
    return res!=null?res.getDeletedCount():0l;

}
 
Example 8
Source File: PersonServiceWithMongo.java    From microprofile-sandbox with Apache License 2.0 5 votes vote down vote up
@DELETE
@Path("/{personId}")
public void removePerson(@PathParam("personId") long id) {
    DeleteResult result = peopleCollection.deleteOne(eq("id", id));
    if (result.getDeletedCount() != 1)
        personNotFound(id);
}
 
Example 9
Source File: MongoClientTemplet.java    From mongodb-orm with Apache License 2.0 5 votes vote down vote up
@Override
public long delete(String statement, Object parameter) {
  if (logger.isDebugEnabled()) {
    logger.debug("Execute 'delete' mongodb command. Statement '" + statement + "'.");
  }

  DeleteConfig config = (DeleteConfig) configuration.getStatement(statement);
  if (config == null) {
    throw new MongoDaoException(statement, "Delete statement id '" + statement + "' not found.");
  }

  String collection = config.getCollection();
  NodeEntry query = config.getQuery();

  MongoDatabase db = getDatabase();
  MongoCollection<Document> coll = db.getCollection(collection).withWriteConcern(WriteConcern.ACKNOWLEDGED);

  Map<String, Object> q = (Map<String, Object>) query.executorNode(config.getNamespace(), configuration, parameter);

  Document filter = new Document(q);
  if (logger.isDebugEnabled()) {
    logger.debug("Execute 'delete' mongodb command. Query '" + filter + "'.");
  }

  DeleteResult result = coll.deleteMany(filter);
  if (!result.wasAcknowledged()) {
    throw new MongoDaoException(statement, "Execute 'delete' mongodb command has exception. The write was unacknowledged.");
  }
  return result.getDeletedCount();
}
 
Example 10
Source File: MongoCollectionImpl.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
@Override
public long delete(Bson filter) {
    var watch = new StopWatch();
    long deletedRows = 0;
    try {
        DeleteResult result = collection().deleteMany(filter == null ? new BsonDocument() : filter);
        deletedRows = result.getDeletedCount();
        return deletedRows;
    } finally {
        long elapsed = watch.elapsed();
        ActionLogContext.track("mongo", elapsed, 0, (int) deletedRows);
        logger.debug("delete, collection={}, filter={}, deletedRows={}, elapsed={}", collectionName, new BsonLogParam(filter, mongo.registry), deletedRows, elapsed);
        checkSlowOperation(elapsed);
    }
}
 
Example 11
Source File: ContentInstanceDAO.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private int deleteOldestNExpired(String containerId, int size) {
		
		log.debug("deleteOldestNExpired containerId:{}, size:{}", containerId, size);
		MongoCollection<Document> collection = context.getDatabaseManager()
				.getCollection(collectionName);
		BasicDBList and = new BasicDBList();
		DeleteResult result;
		/*
		
		String now = LocalDateTime.now().toString(DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss"));
		
		and.add(new BasicDBObject(EXPIRETIME_KEY, new BasicDBObject("$lt", now)));
		and.add(new BasicDBObject(PARENTID_KEY, containerId));
		
		result = collection.deleteMany(new BasicDBObject("$and", and));
		size -= result.getDeletedCount();
		
		log.debug("Deleted expired contentInstance:{}", result.getDeletedCount());
		*/
		
		if (size >= 0) {
			and.clear();	
			and.add(new BasicDBObject(PARENTID_KEY, containerId));
			and.add(new BasicDBObject(RESTYPE_KEY, RESOURCE_TYPE.CONTENT_INST.Value()));
			
			MongoCursor<Document> cursor = collection.find(new BasicDBObject("$and", and))
											.sort(new BasicDBObject(CREATETIME_KEY, 1))
											.limit(size).iterator();
			
			int deletedCount = 0;
			if (cursor.hasNext()) {
				Document doc = cursor.next();
//				and.clear();
//				and.add(new BasicDBObject(PARENTID_KEY, containerId));
//				and.add(new BasicDBObject(RESTYPE_KEY, RESOURCE_TYPE.CONTENT_INST.Value()));
//				and.add(new BasicDBObject(CREATETIME_KEY, new BasicDBObject("$lt", doc.get(CREATETIME_KEY))));
//				
				result = collection.deleteOne(new BasicDBObject(RESID_KEY, doc.get(RESID_KEY)));
	
				deletedCount += result.getDeletedCount();
			}
			log.debug("Deleted oldest contentInstance:{}", deletedCount);
			return deletedCount;
		}
		return 0;
		
	}
 
Example 12
Source File: DeleteManyOperation.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
public SyncDeleteResult execute(@Nullable final CoreStitchServiceClient service) {
  final DeleteResult localResult = this.dataSynchronizer.deleteMany(namespace, filter);
  return new SyncDeleteResult(localResult.getDeletedCount());
}
 
Example 13
Source File: DeleteOneOperation.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
public SyncDeleteResult execute(@Nullable final CoreStitchServiceClient service) {
  final DeleteResult localResult = this.dataSynchronizer.deleteOne(namespace, filter);
  return new SyncDeleteResult(localResult.getDeletedCount());
}
 
Example 14
Source File: MongoOperations.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public static boolean deleteById(Class<?> entityClass, Object id) {
    MongoCollection collection = mongoCollection(entityClass);
    Document query = new Document().append(ID, id);
    DeleteResult results = collection.deleteOne(query);
    return results.getDeletedCount() == 1;
}
 
Example 15
Source File: MongoAccessor.java    From jstarcraft-core with Apache License 2.0 4 votes vote down vote up
@Override
public <K extends Comparable, T extends IdentityObject<K>> boolean deleteInstance(Class<T> clazz, T object) {
	MongoMetadata metadata = metadatas.get(clazz);
	DeleteResult state = template.remove(object, metadata.getOrmName());
	return state.getDeletedCount() > 0;
}
 
Example 16
Source File: DeleteMongo.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();
    final WriteConcern writeConcern = getWriteConcern(context);
    final String deleteMode = context.getProperty(DELETE_MODE).getValue();
    final String deleteAttr = flowFile.getAttribute("mongodb.delete.mode");
    final Boolean failMode  = context.getProperty(FAIL_ON_NO_DELETE).asBoolean();

    if (deleteMode.equals(DELETE_ATTR.getValue())
            && (StringUtils.isEmpty(deleteAttr) || !ALLOWED_DELETE_VALUES.contains(deleteAttr.toLowerCase()) )) {
        getLogger().error(String.format("%s is not an allowed value for mongodb.delete.mode", deleteAttr));
        session.transfer(flowFile, REL_FAILURE);
        return;
    }

    try {
        final MongoCollection<Document> collection = getCollection(context, flowFile).withWriteConcern(writeConcern);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        session.exportTo(flowFile, bos);
        bos.close();

        String json = new String(bos.toByteArray());
        Document query = Document.parse(json);
        DeleteResult result;

        if (deleteMode.equals(DELETE_ONE.getValue())
                || (deleteMode.equals(DELETE_ATTR.getValue()) && deleteAttr.toLowerCase().equals("one") )) {
            result = collection.deleteOne(query);
        } else {
            result = collection.deleteMany(query);
        }

        if (failMode && result.getDeletedCount() == 0) {
            session.transfer(flowFile, REL_FAILURE);
        } else {
            session.transfer(flowFile, REL_SUCCESS);
        }

    } catch (Exception ex) {
        getLogger().error("Could not send a delete to MongoDB, failing...", ex);
        session.transfer(flowFile, REL_FAILURE);
    }
}
 
Example 17
Source File: MongoAccessor.java    From jstarcraft-core with Apache License 2.0 4 votes vote down vote up
@Override
public <K extends Comparable, T extends IdentityObject<K>> boolean deleteInstance(Class<T> clazz, K id) {
	MongoMetadata metadata = metadatas.get(clazz);
	DeleteResult state = template.remove(Query.query(Criteria.where(MongoMetadata.mongoId).is(id)), metadata.getOrmName());
	return state.getDeletedCount() > 0;
}
 
Example 18
Source File: BaseService.java    From HA-DB with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public boolean delete(String collectionName, String id) {
	Query query = Query.query(Criteria.where(Opations.ID_FIELD).is(id));
	DeleteResult result = mongoTemplate.remove(query, collectionName);
	return result.getDeletedCount() > 0;
}
 
Example 19
Source File: ContentInstanceDAO.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private int deleteOldestNExpired(String containerId, int size) {
		
		log.debug("deleteOldestNExpired containerId:{}, size:{}", containerId, size);
		MongoCollection<Document> collection = context.getDatabaseManager()
				.getCollection(collectionName);
		BasicDBList and = new BasicDBList();
		DeleteResult result;
		/*
		
		String now = LocalDateTime.now().toString(DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss"));
		
		and.add(new BasicDBObject(EXPIRETIME_KEY, new BasicDBObject("$lt", now)));
		and.add(new BasicDBObject(PARENTID_KEY, containerId));
		
		result = collection.deleteMany(new BasicDBObject("$and", and));
		size -= result.getDeletedCount();
		
		log.debug("Deleted expired contentInstance:{}", result.getDeletedCount());
		*/
		
		if (size >= 0) {
			and.clear();	
			and.add(new BasicDBObject(PARENTID_KEY, containerId));
			and.add(new BasicDBObject(RESTYPE_KEY, RESOURCE_TYPE.CONTENT_INST.Value()));
			
			MongoCursor<Document> cursor = collection.find(new BasicDBObject("$and", and))
											.sort(new BasicDBObject(CREATETIME_KEY, 1))
											.limit(size).iterator();
			
			int deletedCount = 0;
			if (cursor.hasNext()) {
				Document doc = cursor.next();
//				and.clear();
//				and.add(new BasicDBObject(PARENTID_KEY, containerId));
//				and.add(new BasicDBObject(RESTYPE_KEY, RESOURCE_TYPE.CONTENT_INST.Value()));
//				and.add(new BasicDBObject(CREATETIME_KEY, new BasicDBObject("$lt", doc.get(CREATETIME_KEY))));
//				
				result = collection.deleteOne(new BasicDBObject(RESID_KEY, doc.get(RESID_KEY)));
	
				deletedCount += result.getDeletedCount();
			}
			log.debug("Deleted oldest contentInstance:{}", deletedCount);
			return deletedCount;
		}
		return 0;
		
	}
 
Example 20
Source File: MongoSdkBase.java    From Mongodb-WeAdmin with Apache License 2.0 2 votes vote down vote up
/**
 * 删除找到的第一条记录
 *
 * @param table  表连接
 * @return
 */
public  int deleteOne(MongoCollection table, String id) {
    Bson filter = eq("_id", id);
    DeleteResult re = table.deleteOne(filter);
    return (int) re.getDeletedCount();
}