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

The following examples show how to use com.mongodb.client.MongoCollection#deleteOne() . 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: StatsDao.java    From XBDD with 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 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: MongoConnectionWrapper.java    From mongowp with 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 5
Source File: MongoStorage.java    From LuckPerms with 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 6
Source File: CaseController.java    From skywalking with 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 7
Source File: RestSubscriptionDAO.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 8
Source File: CASAuthDAO.java    From SI with 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 9
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 10
Source File: LegacyQuery.java    From morphia with 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 11
Source File: DefaultHygieiaServiceImpl.java    From ExecDashboard with Apache License 2.0 5 votes vote down vote up
@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 12
Source File: DAO.java    From Babler with 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 13
Source File: MongoOperations.java    From quarkus with 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 14
Source File: MongoDocumentStorage.java    From lumongo with 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 15
Source File: MongoDbDataProviderEngine.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
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 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: DataSynchronizer.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * 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 18
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 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: ClusterHelper.java    From lumongo with 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);

	}