下面列出了com.mongodb.Function#com.mongodb.client.result.DeleteResult 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
void testSingleDocumentDeletion() {
ReactiveMongoDatabase database = client.getDatabase(DATABASE);
ReactiveMongoCollection<Document> collection = database.getCollection(randomAlphaString(8));
List<Document> documents = new ArrayList<>();
for (int i = 0; i < 100; i++) {
documents.add(new Document("i", i));
}
collection.insertMany(documents).await().indefinitely();
DeleteResult result = collection.deleteOne(eq("i", 10)).await().indefinitely();
assertThat(result.getDeletedCount()).isEqualTo(1);
assertThat(collection.find(eq("i", 10)).collectItems().first().await().indefinitely()).isNull();
Long count = collection.countDocuments().await().indefinitely();
assertThat(count).isEqualTo(99);
}
@Test
void testSingleDocumentDeletionWithOptions() {
ReactiveMongoDatabase database = client.getDatabase(DATABASE);
ReactiveMongoCollection<Document> collection = database.getCollection(randomAlphaString(8));
List<Document> documents = new ArrayList<>();
for (int i = 0; i < 100; i++) {
documents.add(new Document("i", i));
}
collection.insertMany(documents).await().indefinitely();
DeleteResult result = collection.deleteOne(eq("i", 10),
new DeleteOptions().collation(
Collation.builder().locale("en").caseLevel(true).build()))
.await().indefinitely();
assertThat(result.getDeletedCount()).isEqualTo(1);
assertThat(collection.find(eq("i", 10)).collectItems().first().await().indefinitely()).isNull();
Long count = collection.countDocuments().await().indefinitely();
assertThat(count).isEqualTo(99);
}
@Test
void testMultipleDocumentDeletion() {
ReactiveMongoDatabase database = client.getDatabase(DATABASE);
ReactiveMongoCollection<Document> collection = database.getCollection(randomAlphaString(8));
List<Document> documents = new ArrayList<>();
for (int i = 0; i < 100; i++) {
documents.add(new Document("i", i));
}
collection.insertMany(documents).await().indefinitely();
DeleteResult result = collection.deleteMany(gte("i", 90)).await().indefinitely();
assertThat(result.getDeletedCount()).isEqualTo(10);
assertThat(collection.find(eq("i", 90)).collectItems().first().await().indefinitely()).isNull();
Long count = collection.countDocuments().await().indefinitely();
assertThat(count).isEqualTo(90);
}
@Test
void testMultipleDocumentDeletionWithOptions() {
ReactiveMongoDatabase database = client.getDatabase(DATABASE);
ReactiveMongoCollection<Document> collection = database.getCollection(randomAlphaString(8));
List<Document> documents = new ArrayList<>();
for (int i = 0; i < 100; i++) {
documents.add(new Document("i", i));
}
collection.insertMany(documents).await().indefinitely();
DeleteResult result = collection.deleteMany(gte("i", 90), new DeleteOptions().collation(
Collation.builder().locale("en").caseLevel(true).build()))
.await().indefinitely();
assertThat(result.getDeletedCount()).isEqualTo(10);
assertThat(collection.find(eq("i", 90)).collectItems().first().await().asOptional().indefinitely()).isEmpty();
Long count = collection.countDocuments().await().indefinitely();
assertThat(count).isEqualTo(90);
}
@Override
public Result<DeleteResult> deleteAuthorList(String objectId) {
ObjectId userId = UserUtils.getUserId();
if (userId == null) {
return new Result<>(ResultEnum.HAS_NOT_LOGGED_IN);
}
AuthorGroup authorGroup = this.getAuthorList(objectId);
if (authorGroup == null) {
return new Result<>(ResultEnum.LIST_NOT_FOUND);
}
if (authorGroup.getMaintainer().getId().toHexString().equals(userId.toHexString())) {
return new Result<>(ResultEnum.SUCCEED, mongoTemplate.remove(Query.query(Criteria.where("_id").is(objectId)), AuthorGroup.class));
} else {
return new Result<>(ResultEnum.EXECUTE_FAILURE);
}
}
public void removeMatchesBetweenGroups(final MatchCollectionId collectionId,
final String pGroupId,
final String qGroupId)
throws IllegalArgumentException, ObjectNotFoundException {
LOG.debug("removeMatchesBetweenGroups: entry, collectionId={}, pGroupId={}, qGroupId={}",
collectionId, pGroupId, qGroupId);
validateRequiredGroupIds(pGroupId, qGroupId);
final MongoCollection<Document> collection = getExistingCollection(collectionId);
final Document query = getNormalizedGroupIdQuery(pGroupId, qGroupId);
final DeleteResult result = collection.deleteMany(query);
LOG.debug("removeMatchesBetweenGroups: removed {} matches using {}.delete({})",
result.getDeletedCount(), MongoUtil.fullName(collection), query.toJson());
}
/**
* 删除记录
*
* @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;
}
}
@Override
public Future<@Nullable MongoClientDeleteResult> removeDocumentWithOptions(String collection, JsonObject query, @Nullable WriteOption writeOption) {
requireNonNull(collection, "collection cannot be null");
requireNonNull(query, "query cannot be null");
MongoCollection<JsonObject> coll = getCollection(collection, writeOption);
Bson bquery = wrap(encodeKeyWhenUseObjectId(query));
Promise<DeleteResult> promise = vertx.promise();
coll.deleteOne(bquery).subscribe(new SingleResultSubscriber<>(promise));
return promise.future().map(Utils::toMongoClientDeleteResult);
}
@DELETE
@Path("/{personId}")
public void removePerson(@PathParam("personId") long id) {
DeleteResult result = peopleCollection.deleteOne(eq("id", id));
if (result.getDeletedCount() != 1)
personNotFound(id);
}
/**
* 删除
*/
@Test
public void deleteTest(){
Query query = Query.query(Criteria.where("user_phone").is("48"));
DeleteResult remove = mongoTemplate.remove(query, SysUser.class);
log.info("delete 影响行数:"+remove.getDeletedCount());
}
/**
* 删除
*/
@Test
public void deleteTest(){
Query query = Query.query(Criteria.where("user_phone").is("48"));
DeleteResult remove = mongoTemplate.remove(query, SysUser.class);
log.info("delete 影响行数:"+remove.getDeletedCount());
}
@DeleteMapping(value = "{id}")
public JsonResult delete(@PathVariable String id) {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(id));
DeleteResult deleteResult = mongoTemplate.remove(query, User.class, "user");
return new JsonResult(true, deleteResult);
}
public void removeStack(final StackId stackId,
final boolean includeMetaData)
throws IllegalArgumentException {
MongoUtil.validateRequiredParameter("stackId", stackId);
final MongoCollection<Document> tileCollection = getTileCollection(stackId);
final long tileCount = tileCollection.count();
tileCollection.drop();
LOG.debug("removeStack: {}.drop() deleted {} document(s)", MongoUtil.fullName(tileCollection), tileCount);
final MongoCollection<Document> transformCollection = getTransformCollection(stackId);
final long transformCount = transformCollection.count();
transformCollection.drop();
LOG.debug("removeStack: {}.drop() deleted {} document(s)",
MongoUtil.fullName(transformCollection), transformCount);
final MongoCollection<Document> sectionCollection = getSectionCollection(stackId);
final long sectionCount = sectionCollection.count();
sectionCollection.drop();
LOG.debug("removeStack: {}.drop() deleted {} document(s)",
MongoUtil.fullName(sectionCollection), sectionCount);
if (includeMetaData) {
final MongoCollection<Document> stackMetaDataCollection = getStackMetaDataCollection();
final Document stackIdQuery = getStackIdQuery(stackId);
final DeleteResult stackMetaDataRemoveResult = stackMetaDataCollection.deleteOne(stackIdQuery);
LOG.debug("removeStack: {}.remove({}) deleted {} document(s)",
MongoUtil.fullName(stackMetaDataCollection),
stackIdQuery.toJson(),
stackMetaDataRemoveResult.getDeletedCount());
}
}
protected final FluentFuture<Integer> doDelete(
final Constraints.ConstraintHost criteria) {
checkNotNull(criteria);
return submit(new Callable<DeleteResult>() {
@Override
public DeleteResult call() {
return collection().deleteMany(convertToBson(criteria));
}
}).lazyTransform(new Function<DeleteResult, Integer>() {
@Override
public Integer apply(DeleteResult input) {
return (int) input.getDeletedCount();
}
});
}
@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();
}
@Override
public DeleteResult delete(final DeleteOptions options) {
MongoCollection<T> collection = options.prepare(getCollection());
ClientSession session = datastore.findSession(options);
if (options.isMulti()) {
return session == null
? collection.deleteMany(getQueryDocument(), options)
: collection.deleteMany(session, getQueryDocument(), options);
} else {
return session == null
? collection.deleteOne(getQueryDocument(), options)
: collection.deleteOne(session, getQueryDocument(), options);
}
}
/**
* 通过过滤条件删除数据
*
* @param dbName
* @param collectionName
* @param filter
* @return
*/
public boolean delete(String dbName, String collectionName, Document filter) {
if (filter != null) {
DeleteResult result = mongoClient.getDatabase(dbName).getCollection(collectionName)
.deleteMany(new Document(filter));
long deletedCount = result.getDeletedCount();
return deletedCount > 0 ? true : false;
}
return false;
}
@DELETE
@Path("/{personId}")
public void removePerson(@PathParam("personId") long id) {
DeleteResult result = peopleCollection.deleteOne(eq("id", id));
if (result.getDeletedCount() != 1)
personNotFound(id);
}
public Mono<DeleteResult> resetJackpot() {
LOGGER.debug("[Lottery] Jackpot deletion");
return Mono.from(this.getCollection()
.deleteOne(Filters.eq("_id", "jackpot")))
.doOnNext(result -> LOGGER.trace("[Lottery] Jackpot deletion result: {}", result))
.doOnTerminate(() -> DB_REQUEST_COUNTER.labels(LotteryCollection.NAME).inc());
}
@Override
public boolean deleteByUserIdAndClientIdAndScope(final MongoApproval mongoApproval) {
final DeleteResult deleteResult = mongoTemplate.remove(byUserIdAndClientIdAndScope(mongoApproval),
MongoApproval.class);
return deleteResult.wasAcknowledged();
}
public void removeMatchesOutsideGroup(final MatchCollectionId collectionId,
final String groupId)
throws IllegalArgumentException, ObjectNotFoundException {
MongoUtil.validateRequiredParameter("groupId", groupId);
final MongoCollection<Document> collection = getExistingCollection(collectionId);
final Document query = getOutsideGroupQuery(groupId);
final DeleteResult result = collection.deleteMany(query);
LOG.debug("removeMatchesOutsideGroup: removed {} matches using {}.delete({})",
result.getDeletedCount(), MongoUtil.fullName(collection), query.toJson());
}
public void removeTile(final StackId stackId,
final String tileId)
throws IllegalArgumentException {
MongoUtil.validateRequiredParameter("stackId", stackId);
MongoUtil.validateRequiredParameter("tileId", tileId);
final MongoCollection<Document> tileCollection = getTileCollection(stackId);
final Document tileQuery = new Document("tileId", tileId);
final DeleteResult removeResult = tileCollection.deleteOne(tileQuery);
LOG.debug("removeTile: {}.remove({}) deleted {} document(s)",
MongoUtil.fullName(tileCollection), tileQuery.toJson(), removeResult.getDeletedCount());
}
@Override
public Publisher<DeleteResult> deleteMany(final ClientSession clientSession, final Bson filter, final DeleteOptions options) {
return new ObservableToPublisher<DeleteResult>(com.mongodb.async.client.Observables.observe(
new Block<com.mongodb.async.SingleResultCallback<DeleteResult>>() {
@Override
public void apply(final com.mongodb.async.SingleResultCallback<DeleteResult> callback) {
wrapped.deleteMany(clientSession.getWrapped(), filter, options, callback);
}
}));
}
public DeleteResult deleteDocument(String keyName, String keyValue) {
MongoCollection<Document> collection = context.getDatabaseManager()
.getCollection(collectionName);
DeleteResult result = collection.deleteMany(new BasicDBObject(keyName,
keyValue));
log.debug(result.toString());
return result;
}
@Test
public void shouldLockWhenDocumentRemovedExternally() {
LockProvider provider = getLockProvider();
assertThat(provider.lock(lockConfig(LOCK_NAME1))).isNotEmpty();
assertLocked(LOCK_NAME1);
DeleteResult result = execute(getLockCollection().deleteOne(eq(ID, LOCK_NAME1)));
assumeThat(result.getDeletedCount()).isEqualTo(1);
assertThat(provider.lock(lockConfig(LOCK_NAME1))).isNotEmpty();
assertLocked(LOCK_NAME1);
}
@Override
public Observable<DeleteResult> deleteOne(final Bson filter) {
return RxObservables.create(Observables.observe(new Block<SingleResultCallback<DeleteResult>>() {
@Override
public void apply(final SingleResultCallback<DeleteResult> callback) {
wrapped.deleteOne(filter, callback);
}
}), observableAdapter);
}
/**
* Deletes the given entity (by @Id), with the WriteConcern
*
* @param entity the entity to delete
* @param options the options to use when deleting
* @return results of the delete
*/
@Override
public <T> DeleteResult delete(final T entity, final DeleteOptions options) {
if (entity instanceof Class<?>) {
throw new MappingException("Did you mean to delete all documents? -- ds.createQuery(???.class).delete()");
}
return find(entity.getClass())
.filter(eq("_id", mapper.getId(entity)))
.delete(options);
}
@Override
public Observable<DeleteResult> deleteMany(final Bson filter, final DeleteOptions options) {
return RxObservables.create(Observables.observe(new Block<SingleResultCallback<DeleteResult>>() {
@Override
public void apply(final SingleResultCallback<DeleteResult> callback) {
wrapped.deleteMany(filter, options, callback);
}
}), observableAdapter);
}
@Override
public void removeCard(MagicCard mc, MagicCollection collection) throws SQLException {
logger.debug("removeCard " + mc + " from " + collection);
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<>();
obj.add(new BasicDBObject(dbIDField, IDGenerator.generate(mc)));
obj.add(new BasicDBObject(dbColIDField, collection.getName()));
andQuery.put("$and", obj);
DeleteResult dr = db.getCollection(colCards, BasicDBObject.class).deleteMany(andQuery);
logger.debug(dr.toString());
}
@Override
public void removeCollection(MagicCollection c) throws SQLException {
logger.debug("remove collection " + c);
BasicDBObject query = new BasicDBObject();
query.put(dbColIDField, c.getName());
DeleteResult dr = db.getCollection(colCards).deleteMany(query);
logger.trace(dr);
db.getCollection(colCollects, MagicCollection.class).deleteOne(Filters.eq("name", c.getName()));
}