Java Code Examples for com.mongodb.client.MongoCollection#deleteOne()

The following examples show how to use com.mongodb.client.MongoCollection#deleteOne() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: grain   File: MongodbManager.java    License: 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 2
Source Project: mongowp   File: MongoConnectionWrapper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void asyncDelete(
    String database,
    String collection,
    boolean singleRemove,
    BsonDocument selector) throws MongoException {
  try {
    MongoCollection<BsonDocument> collectionObject =
        owner.getDriverClient()
            .getDatabase(database)
            .getCollection(collection, BsonDocument.class);
    org.bson.BsonDocument mongoSelector =
        MongoBsonTranslator.translate(selector);
    if (singleRemove) {
      collectionObject.deleteOne(mongoSelector);
    } else {
      collectionObject.deleteMany(mongoSelector);
    }
  } catch (com.mongodb.MongoException ex) { //a general Mongo driver exception
    if (ErrorCode.isErrorCode(ex.getCode())) {
      throw toMongoException(ex);
    } else {
      throw toRuntimeMongoException(ex);
    }
  }
}
 
Example 3
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 4
Source Project: XBDD   File: StatsDao.java    License: Apache License 2.0 6 votes vote down vote up
public void updateStatsForFeatures(final Coordinates coordinates, final List<XbddFeature> features) {
	final MongoCollection<Stats> statsCollection = getStatsCollection();

	// product and version are redundant for search, but ensure they're populated if the upsert results in an insert.
	final String id = coordinates.getProduct() + "/" + coordinates.getVersionString() + "/" + coordinates.getBuild();
	statsCollection.deleteOne(Filters.eq(id));

	final Stats newStats = new Stats();
	newStats.setCoordinates(CoordinatesMapper.mapCoordinates(coordinates));
	newStats.setId(id);
	newStats.setSummary(getNewStatsSummary());

	for (final XbddFeature xbddFeature : features) {
		if (xbddFeature.getElements() != null) {
			for (final XbddScenario scenario : xbddFeature.getElements()) {
				final List<String> stepStatuses = FeatureMapper.getStepStatusStream(scenario).collect(Collectors.toList());
				final String status = StatusHelper.reduceStatuses(stepStatuses).getTextName();
				newStats.getSummary().replace(status, newStats.getSummary().get(status) + 1);
			}
		}
	}
	statsCollection.insertOne(newStats);
}
 
Example 5
@Override
public Boolean deleteUser(String appId, String user) {

	List<Dashboard> dashboardList = null;
	try {
		dashboardList = dashboardRepository.findByappId(appId);

		if (!dashboardList.isEmpty()) {
			for (Dashboard dashboard : dashboardList) {

				BunitCredentials bunitCredential = dashboard.getDbCredentials();
				MongoClient mongoClient = getMongoClient(bunitCredential);
				if (null != mongoClient) {

					MongoDatabase mongoDB = getMongoDatabase(mongoClient, bunitCredential.getDbName());
					if (null != mongoDB) {
						MongoCollection<Document> users = mongoDB.getCollection("authentication");
						if (null != users) {
							DeleteResult deleteResult = users.deleteOne(eq(USERNAME, user));
							LOG.info("deleteOne() - # of records deleted - " + deleteResult.getDeletedCount());
							if (deleteResult.getDeletedCount() != 0) {
								return true;
							} else {
								return false;
							}
						}
					}
				}

			}
		}

	} catch (Exception e) {
		LOG.error(e.getMessage());
	}
	return null;
}
 
Example 6
private Object deleteOne(Map<String, Object> inParams, MongoCollection<Document> collection) {
    if (!inParams.containsKey("id"))
        throw new N2oException("Id is required for operation \"deleteOne\"");

    collection.deleteOne(eq("_id", new ObjectId((String) inParams.get("id"))));
    return null;
}
 
Example 7
Source Project: lumongo   File: MongoDocumentStorage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void deleteSourceDocument(String uniqueId) throws Exception {
	MongoDatabase db = mongoClient.getDatabase(database);
	MongoCollection<Document> coll = db.getCollection(rawCollectionName);
	Document search = new Document(MongoConstants.StandardFields._ID, uniqueId);
	coll.deleteOne(search);
}
 
Example 8
Source Project: quarkus   File: MongoOperations.java    License: Apache License 2.0 5 votes vote down vote up
public static void delete(Object entity) {
    MongoCollection collection = mongoCollection(entity);
    BsonDocument document = getBsonDocument(collection, entity);
    BsonValue id = document.get(ID);
    BsonDocument query = new BsonDocument().append(ID, id);
    collection.deleteOne(query);
}
 
Example 9
Source Project: Babler   File: DAO.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * deletes an entry from the DB
 * @param entry to delete
 */
public static void deleteEntry(DBEntry entry) {
    if(entry == null)
        return;

    MongoDatabase db = MongoDB.INSTANCE.getDatabase("scraping");
    String collectionName = getCollectionName(entry);

    MongoCollection collection = db.getCollection(collectionName, BasicDBObject.class);
    collection.deleteOne(eq("_id",entry.getId()));
}
 
Example 10
Source Project: LuckPerms   File: MongoStorage.java    License: MIT License 5 votes vote down vote up
@Override
public void deleteGroup(Group group) {
    group.getIoLock().lock();
    try {
        MongoCollection<Document> c = this.database.getCollection(this.prefix + "groups");
        c.deleteOne(new Document("_id", group.getName()));
    } finally {
        group.getIoLock().unlock();
    }
}
 
Example 11
Source Project: morphia   File: LegacyQuery.java    License: Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 12
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 13
Source Project: SI   File: CASAuthDAO.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void deleteAuthInfo(String devId) {
	MongoCollection<Document> collection = context.getDatabaseManager().getCollection(collectionName);
	
	Document authDoc = getDocument(AUTH_KEY_NAME, devId);
	if(authDoc != null) {
		collection.deleteOne(authDoc);
	}
	
}
 
Example 14
public void delSubscription(String uri, String notificationUri) {
	
	MongoCollection<Document> collection = dbManager.getCollection(collectionName);
	Document seqDoc = getDocument(URI_KEY, uri);
	
	if(seqDoc != null) {
		collection.deleteOne(seqDoc);
	}
}
 
Example 15
Source Project: skywalking   File: CaseController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping("/mongodb")
public String mongoDBCase() {
    try (MongoClient mongoClient = new MongoClient(host, port)) {
        MongoDatabase db = mongoClient.getDatabase("test-database");
        // CreateCollectionOperation
        db.createCollection("testCollection");

        MongoCollection<Document> collection = db.getCollection("testCollection");
        Document document = Document.parse("{id: 1, name: \"test\"}");
        // MixedBulkWriteOperation
        collection.insertOne(document);

        // FindOperation
        FindIterable<Document> findIterable = collection.find(eq("name", "org"));
        findIterable.first();

        // MixedBulkWriteOperation
        collection.updateOne(eq("name", "org"), BsonDocument.parse("{ $set : { \"name\": \"testA\"} }"));

        // FindOperation
        findIterable = collection.find(eq("name", "testA"));
        findIterable.first();

        // MixedBulkWriteOperation
        collection.deleteOne(eq("id", "1"));

        // DropDatabaseOperation
        mongoClient.dropDatabase("test-database");
    }
    return "success";
}
 
Example 16
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 17
Source Project: quarkus   File: MongoOperations.java    License: 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 18
/**
 * Removes at most one document from the collection that matches the given filter.  If no
 * documents match, the collection is not
 * modified.
 *
 * @param filter the query filter to apply the the delete operation
 * @return the result of the remove one operation
 */
DeleteResult deleteOne(final MongoNamespace namespace, final Bson filter) {
  this.waitUntilInitialized();

  try {
    ongoingOperationsGroup.enter();
    final ChangeEvent<BsonDocument> event;
    final DeleteResult result;
    final NamespaceSynchronizationConfig nsConfig =
        this.syncConfig.getNamespaceConfig(namespace);
    nsConfig.getLock().writeLock().lock();
    try {
      final MongoCollection<BsonDocument> localCollection = getLocalCollection(namespace);
      final BsonDocument docToDelete = localCollection
          .find(filter)
          .first();

      if (docToDelete == null) {
        return DeleteResult.acknowledged(0);
      }

      final BsonValue documentId = BsonUtils.getDocumentId(docToDelete);
      final CoreDocumentSynchronizationConfig config =
          syncConfig.getSynchronizedDocument(namespace, documentId);

      if (config == null) {
        return DeleteResult.acknowledged(0);
      }

      final MongoCollection<BsonDocument> undoCollection = getUndoCollection(namespace);
      undoCollection.insertOne(docToDelete);

      result = localCollection.deleteOne(filter);
      event = ChangeEvents.changeEventForLocalDelete(namespace, documentId, true);

      // this block is to trigger coalescence for a delete after insert
      if (config.getLastUncommittedChangeEvent() != null
          && config.getLastUncommittedChangeEvent().getOperationType()
          == OperationType.INSERT) {
        final LocalSyncWriteModelContainer localSyncWriteModelContainer =
            desyncDocumentsFromRemote(nsConfig, config.getDocumentId());
        localSyncWriteModelContainer.commitAndClear();

        // delete the namespace listener if necessary
        checkAndDeleteNamespaceListener(namespace);
        undoCollection.deleteOne(getDocumentIdFilter(config.getDocumentId()));
        return result;
      }

      config.setSomePendingWritesAndSave(logicalT, event);
      undoCollection.deleteOne(getDocumentIdFilter(config.getDocumentId()));
    } finally {
      nsConfig.getLock().writeLock().unlock();
    }
    eventDispatcher.emitEvent(nsConfig, event);
    return result;
  } finally {
    ongoingOperationsGroup.exit();
  }
}
 
Example 19
Source Project: nifi   File: DeleteMongo.java    License: 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 20
Source Project: lumongo   File: ClusterHelper.java    License: Apache License 2.0 3 votes vote down vote up
public void removeClusterConfig() throws UnknownHostException, MongoException {

		MongoDatabase db = mongo.getDatabase(database);

		MongoCollection<Document> configCollection = db.getCollection(CLUSTER_CONFIG);

		Document search = new Document();
		search.put(_ID, CLUSTER);

		configCollection.deleteOne(search);

	}