Example usage for com.mongodb.client MongoCollection deleteOne

List of usage examples for com.mongodb.client MongoCollection deleteOne

Introduction

In this page you can find the example usage for com.mongodb.client MongoCollection deleteOne.

Prototype

DeleteResult deleteOne(Bson filter);

Source Link

Document

Removes at most one document from the collection that matches the given filter.

Usage

From source file:org.restheart.db.CollectionDAO.java

License:Open Source License

/**
 * Deletes a collection./*from   w  w w  .j  av a 2  s .c o m*/
 *
 * @param dbName the database name of the collection
 * @param collName the collection name
 * @param requestEtag the entity tag. must match to allow actual write
 * (otherwise http error code is returned)
 * @return the HttpStatus code to set in the http response
 */
OperationResult deleteCollection(final String dbName, final String collName, final String requestEtag,
        final boolean checkEtag) {
    MongoDatabase mdb = client.getDatabase(dbName);
    MongoCollection<Document> mcoll = mdb.getCollection("_properties");

    if (checkEtag) {
        Document properties = mcoll.find(eq("_id", "_properties.".concat(collName)))
                .projection(FIELDS_TO_RETURN).first();

        if (properties != null) {
            Object oldEtag = properties.get("_etag");

            if (oldEtag != null) {
                if (requestEtag == null) {
                    return new OperationResult(HttpStatus.SC_CONFLICT, oldEtag);
                } else if (!Objects.equals(oldEtag.toString(), requestEtag)) {
                    return new OperationResult(HttpStatus.SC_PRECONDITION_FAILED, oldEtag);
                }
            }
        }
    }

    MongoCollection<Document> collToDelete = mdb.getCollection(collName);
    collToDelete.drop();
    mcoll.deleteOne(eq("_id", "_properties.".concat(collName)));
    return new OperationResult(HttpStatus.SC_NO_CONTENT);
}

From source file:org.restheart.handlers.metadata.AfterWriteCheckHandler.java

License:Open Source License

@Override
public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception {
    if ((doesCheckersApply(context) && !applyCheckers(exchange, context))
            || (doesGlobalCheckersApply() && !applyGlobalCheckers(exchange, context))) {
        // restore old data

        MongoClient client = MongoDBClientSingleton.getInstance().getClient();

        MongoDatabase mdb = client.getDatabase(context.getDBName());

        MongoCollection<BsonDocument> coll = mdb.getCollection(context.getCollectionName(), BsonDocument.class);

        BsonDocument oldData = context.getDbOperationResult().getOldData();

        Object newEtag = context.getDbOperationResult().getEtag();

        if (oldData != null) {
            // document was updated, restore old one
            DAOUtils.restoreDocument(context.getClientSession(), coll, oldData.get("_id"),
                    context.getShardKey(), oldData, newEtag, "_etag");

            // add to response old etag
            if (oldData.get("$set") != null && oldData.get("$set").isDocument()
                    && oldData.get("$set").asDocument().get("_etag") != null) {
                exchange.getResponseHeaders().put(Headers.ETAG,
                        oldData.get("$set").asDocument().get("_etag").asObjectId().getValue().toString());
            } else {
                exchange.getResponseHeaders().remove(Headers.ETAG);
            }//from   w ww . j a va2 s  .  c o  m

        } else {
            // document was created, delete it
            Object newId = context.getDbOperationResult().getNewData().get("_id");

            coll.deleteOne(and(eq("_id", newId), eq("_etag", newEtag)));
        }

        ResponseHelper.endExchangeWithMessage(exchange, context, HttpStatus.SC_BAD_REQUEST,
                "request check failed");
        next(exchange, context);
        return;
    }

    next(exchange, context);
}

From source file:org.restheart.handlers.metadata.AfterWriteCheckMetadataHandler.java

License:Open Source License

@Override
public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception {
    if (doesCheckerAppy(context)) {
        if (!check(exchange, context)) {
            // restore old data

            MongoClient client = MongoDBClientSingleton.getInstance().getClient();

            MongoDatabase mdb = client.getDatabase(context.getDBName());

            MongoCollection<BsonDocument> coll = mdb.getCollection(context.getCollectionName(),
                    BsonDocument.class);

            BsonDocument oldData = context.getDbOperationResult().getOldData();

            Object newEtag = context.getDbOperationResult().getEtag();

            if (oldData != null) {
                // document was updated, restore old one
                DAOUtils.restoreDocument(coll, oldData.get("_id"), context.getShardKey(), oldData, newEtag);

                // add to response old etag
                if (oldData.get("$set") != null && oldData.get("$set").isDocument()
                        && oldData.get("$set").asDocument().get("_etag") != null) {
                    exchange.getResponseHeaders().put(Headers.ETAG,
                            oldData.get("$set").asDocument().get("_etag").asObjectId().getValue().toString());
                } else {
                    exchange.getResponseHeaders().remove(Headers.ETAG);
                }//from   ww w .  j  a  va  2 s  .  co m

            } else {
                // document was created, delete it
                Object newId = context.getDbOperationResult().getNewData().get("_id");

                coll.deleteOne(and(eq("_id", newId), eq("_etag", newEtag)));
            }

            ResponseHelper.endExchangeWithMessage(exchange, context, HttpStatus.SC_BAD_REQUEST,
                    "request check failed");
            next(exchange, context);
            return;
        }
    }

    next(exchange, context);
}

From source file:org.trade.core.persistence.local.mongo.MongoPersistence.java

License:Apache License

@Override
public void storeBinaryData(byte[] data, String collectionName, String identifier) throws Exception {
    MongoClient client = new MongoClient(new MongoClientURI(this.mongoUrl));
    MongoDatabase db = client.getDatabase(this.dbName);

    MongoCollection<Document> collection = db.getCollection(collectionName);
    Document doc = collection.find(Filters.eq(IDENTIFIER_FIELD, identifier)).limit(1).first();

    if (data == null) {
        // We assume that if the value is set to null, we should delete also the corresponding database entry
        if (doc != null) {
            collection.deleteOne(Filters.eq(IDENTIFIER_FIELD, identifier));
        }//from ww w.j  a  va  2  s  .  c  om
    } else {
        // Check if the document already exists and update it
        if (doc != null) {
            collection.updateOne(Filters.eq(IDENTIFIER_FIELD, identifier),
                    Updates.combine(Updates.set(DATA_FIELD, data), Updates.currentDate("lastModified")));
        } else {
            Document document = new Document(IDENTIFIER_FIELD, identifier).append(DATA_FIELD, data)
                    .append("lastModified", new Date());
            collection.insertOne(document);
        }
    }

    client.close();
}

From source file:rapture.lock.mongodb.MongoLockHandler2.java

License:Open Source License

private Boolean releaseLockWithID(String lockName, String id) {
    Document lockFileQuery = new Document();
    lockFileQuery.put("_id", id);
    MongoCollection<Document> coll = getLockCollection(lockName);
    DeleteResult res = coll.deleteOne(lockFileQuery);

    return (res.getDeletedCount() == 1);
}

From source file:rocks.devonthe.stickychunk.database.MongodbDatabase.java

License:GNU General Public License

public void deleteRegionData(LoadedRegion region) {
    MongoCollection<Document> collection = getDatabase().getCollection("chunks");

    Bson condition = new Document("_id", region.getUniqueId().toString());
    collection.deleteOne(condition);
}

From source file:rocks.devonthe.stickychunk.database.MongodbDatabase.java

License:GNU General Public License

public void deleteUserData(UserData userData) {
    MongoCollection<Document> collection = getDatabase().getCollection("users");

    Bson condition = new Document("_id", userData.getUniqueId().toString());
    collection.deleteOne(condition);
}

From source file:tour.PojoQuickTour.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 *///w  w w . ja v a 2s.c o  m
public static void main(final String[] args) {
    MongoClient mongoClient;

    if (args.length == 0) {
        // connect to the local database server
        mongoClient = MongoClients.create();
    } else {
        mongoClient = MongoClients.create(args[0]);
    }

    // create codec registry for POJOs
    CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
            fromProviders(PojoCodecProvider.builder().automatic(true).build()));

    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb").withCodecRegistry(pojoCodecRegistry);

    // get a handle to the "people" collection
    MongoCollection<Person> collection = database.getCollection("people", Person.class);

    // drop all the data in it
    collection.drop();

    // make a document and insert it
    Person ada = new Person("Ada Byron", 20, new Address("St James Square", "London", "W1"));
    System.out.println("Original Person Model: " + ada);
    collection.insertOne(ada);

    // Person will now have an ObjectId
    System.out.println("Mutated Person Model: " + ada);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    Person somebody = collection.find().first();
    System.out.println(somebody);

    // now, lets add some more people so we can explore queries and cursors
    List<Person> people = asList(
            new Person("Charles Babbage", 45, new Address("5 Devonshire Street", "London", "W11")),
            new Person("Alan Turing", 28, new Address("Bletchley Hall", "Bletchley Park", "MK12")),
            new Person("Timothy Berners-Lee", 61, new Address("Colehill", "Wimborne", null)));

    collection.insertMany(people);
    System.out.println("total # of people " + collection.countDocuments());

    System.out.println("");
    // lets get all the documents in the collection and print them out
    Block<Person> printBlock = new Block<Person>() {
        @Override
        public void apply(final Person person) {
            System.out.println(person);
        }
    };

    collection.find().forEach(printBlock);

    System.out.println("");
    // now use a query to get 1 document out
    somebody = collection.find(eq("address.city", "Wimborne")).first();
    System.out.println(somebody);

    System.out.println("");
    // now lets find every over 30
    collection.find(gt("age", 30)).forEach(printBlock);

    System.out.println("");
    // Update One
    collection.updateOne(eq("name", "Ada Byron"), combine(set("age", 23), set("name", "Ada Lovelace")));

    System.out.println("");
    // Update Many
    UpdateResult updateResult = collection.updateMany(not(eq("zip", null)), set("zip", null));
    System.out.println(updateResult.getModifiedCount());

    System.out.println("");
    // Replace One
    updateResult = collection.replaceOne(eq("name", "Ada Lovelace"), ada);
    System.out.println(updateResult.getModifiedCount());

    // Delete One
    collection.deleteOne(eq("address.city", "Wimborne"));

    // Delete Many
    DeleteResult deleteResult = collection.deleteMany(eq("address.city", "London"));
    System.out.println(deleteResult.getDeletedCount());

    // Clean up
    database.drop();

    // release resources
    mongoClient.close();
}