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

The following examples show how to use com.mongodb.client.MongoCollection#deleteMany() . 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: MongoAdapterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static void populate(MongoCollection<Document> collection, URL resource)
    throws IOException {
  Objects.requireNonNull(collection, "collection");

  if (collection.countDocuments() > 0) {
    // delete any existing documents (run from a clean set)
    collection.deleteMany(new BsonDocument());
  }

  MongoCollection<BsonDocument> bsonCollection = collection.withDocumentClass(BsonDocument.class);
  Resources.readLines(resource, StandardCharsets.UTF_8, new LineProcessor<Void>() {
    @Override public boolean processLine(String line) throws IOException {
      bsonCollection.insertOne(BsonDocument.parse(line));
      return true;
    }

    @Override public Void getResult() {
      return null;
    }
  });
}
 
Example 2
Source File: MatchDao.java    From render with GNU General Public License v2.0 6 votes vote down vote up
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());
}
 
Example 3
Source File: MatchDao.java    From render with GNU General Public License v2.0 6 votes vote down vote up
public void removeMatchesBetweenTiles(final MatchCollectionId collectionId,
                                      final String pGroupId,
                                      final String pId,
                                      final String qGroupId,
                                      final String qId)
        throws IllegalArgumentException, ObjectNotFoundException {

    LOG.debug("removeMatchesBetweenTiles: entry, collectionId={}, pGroupId={}, pId={}, qGroupId={}, qId={}",
              collectionId, pGroupId, pId, qGroupId, qId);

    validateRequiredPairIds(pGroupId, pId, qGroupId, qId);
    final MongoCollection<Document> collection = getExistingCollection(collectionId);
    final Document query = getNormalizedIdQuery(pGroupId, pId, qGroupId, qId);

    final DeleteResult result = collection.deleteMany(query);

    LOG.debug("removeMatchesBetweenTiles: removed {} matches using {}.delete({})",
              result.getDeletedCount(), MongoUtil.fullName(collection), query.toJson());
}
 
Example 4
Source File: MatchDao.java    From render with GNU General Public License v2.0 6 votes vote down vote up
public void removeMatchesInvolvingObject(final MatchCollectionId collectionId,
                                         final String groupId,
                                         final String id)
        throws IllegalArgumentException, ObjectNotFoundException {

    LOG.debug("removeMatchesInvolvingObject: entry, collectionId={}, groupId={}, id={}",
              collectionId, groupId, id);

    validateRequiredCanvasIds(groupId, id);
    final MongoCollection<Document> collection = getExistingCollection(collectionId);
    final Document query = getInvolvingObjectQuery(groupId, id);

    final DeleteResult result = collection.deleteMany(query);

    LOG.debug("removeMatchesInvolvingObject: removed {} matches using {}.delete({})",
              result.getDeletedCount(), MongoUtil.fullName(collection), query.toJson());
}
 
Example 5
Source File: RenderDao.java    From render with GNU General Public License v2.0 6 votes vote down vote up
void removeTilesWithIds(final StackId stackId,
                        final List<String> tileIds)
        throws IllegalArgumentException {

    MongoUtil.validateRequiredParameter("stackId", stackId);
    MongoUtil.validateRequiredParameter("tileIds", tileIds);

    final MongoCollection<Document> tileCollection = getTileCollection(stackId);
    final Document tileQuery = new Document("tileId",
                                            new Document(QueryOperators.IN,
                                                         tileIds));
    final Document tileQueryForLog = new Document("tileId",
                                                  new Document(QueryOperators.IN,
                                                               Arrays.asList("list of",
                                                                             tileIds.size() + " tileIds")));
    final DeleteResult removeResult = tileCollection.deleteMany(tileQuery);

    LOG.debug("removeTilesWithIds: {}.remove({}) deleted {} document(s)",
              MongoUtil.fullName(tileCollection), tileQueryForLog.toJson(), removeResult.getDeletedCount());
}
 
Example 6
Source File: RenderDao.java    From render with GNU General Public License v2.0 5 votes vote down vote up
public void removeTilesWithZ(final StackId stackId,
                             final Double z)
        throws IllegalArgumentException {

    MongoUtil.validateRequiredParameter("stackId", stackId);
    MongoUtil.validateRequiredParameter("z", z);

    final MongoCollection<Document> tileCollection = getTileCollection(stackId);
    final Document tileQuery = new Document("z", z);
    final DeleteResult removeResult = tileCollection.deleteMany(tileQuery);

    LOG.debug("removeTilesWithZ: {}.remove({}) deleted {} document(s)",
              MongoUtil.fullName(tileCollection), tileQuery.toJson(), removeResult.getDeletedCount());
}
 
Example 7
Source File: MorphiaQuery.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 8
Source File: MatchDao.java    From render with GNU General Public License v2.0 5 votes vote down vote up
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());
}
 
Example 9
Source File: MongoDocumentStorage.java    From lumongo with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteAllDocuments() {
	GridFSBucket gridFS = createGridFSConnection();
	gridFS.drop();

	MongoDatabase db = mongoClient.getDatabase(database);
	MongoCollection<Document> coll = db.getCollection(rawCollectionName);
	coll.deleteMany(new Document());
}
 
Example 10
Source File: RenderDao.java    From render with GNU General Public License v2.0 5 votes vote down vote up
public void removeTilesWithSectionId(final StackId stackId,
                                     final String sectionId)
        throws IllegalArgumentException {

    MongoUtil.validateRequiredParameter("stackId", stackId);
    MongoUtil.validateRequiredParameter("sectionId", sectionId);

    final MongoCollection<Document> tileCollection = getTileCollection(stackId);
    final Document tileQuery = new Document("layout.sectionId", sectionId);
    final DeleteResult removeResult = tileCollection.deleteMany(tileQuery);

    LOG.debug("removeTilesWithSectionId: {}.remove({}) deleted {} document(s)",
              MongoUtil.fullName(tileCollection), tileQuery.toJson(), removeResult.getDeletedCount());
}
 
Example 11
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 12
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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;
	}
 
Example 13
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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;
	}
 
Example 14
Source File: DeleteAllOperation.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(final MongoDatabase connection, final Document data) {
    for (final String collectionName : data.keySet()) {
        final MongoCollection<Document> collection = connection.getCollection(collectionName);
        collection.deleteMany(new Document());
    }
}
 
Example 15
Source File: MongoStorage.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public PlayerSaveResult savePlayerData(UUID uniqueId, String username) {
    username = username.toLowerCase();
    MongoCollection<Document> c = this.database.getCollection(this.prefix + "uuid");

    // find any existing mapping
    String oldUsername = getPlayerName(uniqueId);

    // do the insert
    if (!username.equalsIgnoreCase(oldUsername)) {
        c.replaceOne(new Document("_id", uniqueId), new Document("_id", uniqueId).append("name", username), new ReplaceOptions().upsert(true));
    }

    PlayerSaveResultImpl result = PlayerSaveResultImpl.determineBaseResult(username, oldUsername);

    Set<UUID> conflicting = new HashSet<>();
    try (MongoCursor<Document> cursor = c.find(new Document("name", username)).iterator()) {
        while (cursor.hasNext()) {
            conflicting.add(getDocumentId(cursor.next()));
        }
    }
    conflicting.remove(uniqueId);

    if (!conflicting.isEmpty()) {
        // remove the mappings for conflicting uuids
        c.deleteMany(Filters.and(conflicting.stream().map(u -> Filters.eq("_id", u)).collect(Collectors.toList())));
        result = result.withOtherUuidsPresent(conflicting);
    }

    return result;
}
 
Example 16
Source File: MongoImpl.java    From tephra with MIT License 5 votes vote down vote up
@Override
public void delete(String key, String collection, JSONObject where) {
    MongoCollection<Document> mc = getCollection(key, collection);
    if (mc == null)
        return;

    mc.deleteMany(toDocument(where));
}
 
Example 17
Source File: MatchDao.java    From render with GNU General Public License v2.0 4 votes vote down vote up
public void removeMatchesWithPGroup(final MatchCollectionId collectionId,
                                    final String pGroupId)
        throws IllegalArgumentException, ObjectNotFoundException {

    LOG.debug("removeMatchesWithPGroup: entry, collectionId={}, pGroupId={}",
              collectionId, pGroupId);

    MongoUtil.validateRequiredParameter("pGroupId", pGroupId);

    final MongoCollection<Document> collection = getExistingCollection(collectionId);

    final Document query = new Document("pGroupId", pGroupId);

    final DeleteResult result = collection.deleteMany(query);

    LOG.debug("removeMatchesWithPGroup: removed {} matches using {}.delete({})",
              result.getDeletedCount(), MongoUtil.fullName(collection), query.toJson());
}
 
Example 18
Source File: QueryConverter.java    From sql-to-mongo-db-query-converter with Apache License 2.0 4 votes vote down vote up
/**
 * @param mongoDatabase the database to run the query against.
 * @param <T> variable based on the type of query run.
 * @return When query does a find will return QueryResultIterator&lt;{@link org.bson.Document}&gt;
 *           When query does a count will return a Long
 *           When query does a distinct will return QueryResultIterator&lt;{@link java.lang.String}&gt;
 * @throws ParseException when the sql query cannot be parsed
 */
@SuppressWarnings("unchecked")
public <T> T run(MongoDatabase mongoDatabase) throws ParseException {
    MongoDBQueryHolder mongoDBQueryHolder = getMongoQuery();

    MongoCollection mongoCollection = mongoDatabase.getCollection(mongoDBQueryHolder.getCollection());

    if (SQLCommandType.SELECT.equals(mongoDBQueryHolder.getSqlCommandType())) {
    	
        if (mongoDBQueryHolder.isDistinct()) {
            return (T) new QueryResultIterator<>(mongoCollection.distinct(getDistinctFieldName(mongoDBQueryHolder), mongoDBQueryHolder.getQuery(), String.class));
        } else if (sqlCommandInfoHolder.isCountAll() && !isAggregate(mongoDBQueryHolder)) {
            return (T) Long.valueOf(mongoCollection.count(mongoDBQueryHolder.getQuery()));
        } else if (isAggregate(mongoDBQueryHolder)) {
            
            AggregateIterable aggregate = mongoCollection.aggregate(generateAggSteps(mongoDBQueryHolder,sqlCommandInfoHolder));

            if (aggregationAllowDiskUse != null) {
                aggregate.allowDiskUse(aggregationAllowDiskUse);
            }

            if (aggregationBatchSize != null) {
                aggregate.batchSize(aggregationBatchSize);
            }

            return (T) new QueryResultIterator<>(aggregate);
        } else {
            FindIterable findIterable = mongoCollection.find(mongoDBQueryHolder.getQuery()).projection(mongoDBQueryHolder.getProjection());
            if (mongoDBQueryHolder.getSort() != null && mongoDBQueryHolder.getSort().size() > 0) {
                findIterable.sort(mongoDBQueryHolder.getSort());
            }
            if (mongoDBQueryHolder.getOffset() != -1) {
                findIterable.skip((int) mongoDBQueryHolder.getOffset());
            }
            if (mongoDBQueryHolder.getLimit() != -1) {
                findIterable.limit((int) mongoDBQueryHolder.getLimit());
            }

            return (T) new QueryResultIterator<>(findIterable);
        }
    } else if (SQLCommandType.DELETE.equals(mongoDBQueryHolder.getSqlCommandType())) {
        DeleteResult deleteResult = mongoCollection.deleteMany(mongoDBQueryHolder.getQuery());
        return (T)((Long)deleteResult.getDeletedCount());
    } else {
        throw new UnsupportedOperationException("SQL command type not supported");
    }
}
 
Example 19
Source File: MongoDirectory.java    From lumongo with Apache License 2.0 4 votes vote down vote up
@Override
public void deleteFile(NosqlFile nosqlFile) throws IOException {
	MongoCollection<Document> c = getFilesCollection();

	Document query = new Document();
	query.put(FILE_NUMBER, nosqlFile.getFileNumber());
	c.deleteMany(query);

	MongoCollection<Document> b = getBlocksCollection();
	b.deleteMany(query);

	nameToFileMap.remove(nosqlFile.getFileName());

	nosqlFile.close();

}
 
Example 20
Source File: ClusterHelper.java    From lumongo with Apache License 2.0 3 votes vote down vote up
public void removeNode(String serverAddress, int hazelcastPort) throws Exception {

		MongoDatabase db = mongo.getDatabase(database);

		MongoCollection<Document> membershipCollection = db.getCollection(CLUSTER_MEMBERSHIP);

		Document search = new Document();
		search.put(SERVER_ADDRESS, serverAddress);
		search.put(INSTANCE, hazelcastPort);

		membershipCollection.deleteMany(search);

	}