Search in sources :

Example 11 with DeleteResult

use of com.mongodb.client.result.DeleteResult in project mongo-java-driver by mongodb.

the class PojoQuickTour method main.

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 */
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(MongoClients.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
    final MongoCollection<Person> collection = database.getCollection("people", Person.class);
    // drop all the data in it
    ObservableSubscriber<Void> successSubscriber = new OperationSubscriber<>();
    collection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // make a document and insert it
    final Person ada = new Person("Ada Byron", 20, new Address("St James Square", "London", "W1"));
    System.out.println("Original Person Model: " + ada);
    ObservableSubscriber<InsertOneResult> insertOneSubscriber = new OperationSubscriber<>();
    collection.insertOne(ada).subscribe(insertOneSubscriber);
    insertOneSubscriber.await();
    // get it (since it's the only one in there since we dropped the rest earlier on)
    ObservableSubscriber<Person> personSubscriber = new PrintToStringSubscriber<>();
    collection.find().first().subscribe(personSubscriber);
    personSubscriber.await();
    // 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)));
    ObservableSubscriber<InsertManyResult> insertManySubscriber = new OperationSubscriber<>();
    collection.insertMany(people).subscribe(insertManySubscriber);
    insertManySubscriber.await();
    // get all the documents in the collection and print them out
    personSubscriber = new PrintToStringSubscriber<>();
    collection.find().subscribe(personSubscriber);
    personSubscriber.await();
    // now use a query to get 1 document out
    personSubscriber = new PrintToStringSubscriber<>();
    collection.find(eq("address.city", "Wimborne")).first().subscribe(personSubscriber);
    personSubscriber.await();
    // now lets find every over 30
    personSubscriber = new PrintToStringSubscriber<>();
    collection.find(gt("age", 30)).subscribe(personSubscriber);
    personSubscriber.await();
    // Update One
    ObservableSubscriber<UpdateResult> updateSubscriber = new OperationSubscriber<>();
    collection.updateOne(eq("name", "Ada Byron"), combine(set("age", 23), set("name", "Ada Lovelace"))).subscribe(updateSubscriber);
    updateSubscriber.await();
    // Update Many
    updateSubscriber = new OperationSubscriber<>();
    collection.updateMany(not(eq("zip", null)), set("zip", null)).subscribe(updateSubscriber);
    updateSubscriber.await();
    // Replace One
    updateSubscriber = new OperationSubscriber<>();
    collection.replaceOne(eq("name", "Ada Lovelace"), ada).subscribe(updateSubscriber);
    updateSubscriber.await();
    // Delete One
    ObservableSubscriber<DeleteResult> deleteSubscriber = new OperationSubscriber<>();
    collection.deleteOne(eq("address.city", "Wimborne")).subscribe(deleteSubscriber);
    deleteSubscriber.await();
    // Delete Many
    deleteSubscriber = new OperationSubscriber<>();
    collection.deleteMany(eq("address.city", "London")).subscribe(deleteSubscriber);
    deleteSubscriber.await();
    // Clean up
    successSubscriber = new OperationSubscriber<>();
    database.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // release resources
    mongoClient.close();
}
Also used : OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) InsertManyResult(com.mongodb.client.result.InsertManyResult) MongoClient(com.mongodb.reactivestreams.client.MongoClient) InsertOneResult(com.mongodb.client.result.InsertOneResult) CodecRegistry(org.bson.codecs.configuration.CodecRegistry) PrintToStringSubscriber(reactivestreams.helpers.SubscriberHelpers.PrintToStringSubscriber) UpdateResult(com.mongodb.client.result.UpdateResult) DeleteResult(com.mongodb.client.result.DeleteResult) MongoDatabase(com.mongodb.reactivestreams.client.MongoDatabase)

Example 12 with DeleteResult

use of com.mongodb.client.result.DeleteResult in project mongo-java-driver by mongodb.

the class GridFSBucketImpl method executeDelete.

private void executeDelete(@Nullable final ClientSession clientSession, final BsonValue id) {
    DeleteResult result;
    if (clientSession != null) {
        result = filesCollection.deleteOne(clientSession, new BsonDocument("_id", id));
        chunksCollection.deleteMany(clientSession, new BsonDocument("files_id", id));
    } else {
        result = filesCollection.deleteOne(new BsonDocument("_id", id));
        chunksCollection.deleteMany(new BsonDocument("files_id", id));
    }
    if (result.wasAcknowledged() && result.getDeletedCount() == 0) {
        throw new MongoGridFSException(format("No file found with the id: %s", id));
    }
}
Also used : BsonDocument(org.bson.BsonDocument) MongoGridFSException(com.mongodb.MongoGridFSException) DeleteResult(com.mongodb.client.result.DeleteResult)

Example 13 with DeleteResult

use of com.mongodb.client.result.DeleteResult in project mongo-java-driver by mongodb.

the class QuickTour method main.

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 */
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]);
    }
    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb");
    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");
    // drop all the data in it
    collection.drop();
    // make a document and insert it
    Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1).append("info", new Document("x", 203).append("y", 102));
    collection.insertOne(doc);
    // get it (since it's the only one in there since we dropped the rest earlier on)
    Document myDoc = collection.find().first();
    System.out.println(myDoc.toJson());
    // now, lets add lots of little documents to the collection so we can explore queries and cursors
    List<Document> documents = new ArrayList<Document>();
    for (int i = 0; i < 100; i++) {
        documents.add(new Document("i", i));
    }
    collection.insertMany(documents);
    System.out.println("total # of documents after inserting 100 small ones (should be 101) " + collection.countDocuments());
    // find first
    myDoc = collection.find().first();
    System.out.println(myDoc.toJson());
    // lets get all the documents in the collection and print them out
    MongoCursor<Document> cursor = collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }
    for (Document cur : collection.find()) {
        System.out.println(cur.toJson());
    }
    // now use a query to get 1 document out
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc.toJson());
    // now use a range query to get a larger subset
    cursor = collection.find(gt("i", 50)).iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }
    // range query with multiple constraints
    cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }
    // Query Filters
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc.toJson());
    // now use a range query to get a larger subset
    Consumer<Document> printBlock = new Consumer<Document>() {

        @Override
        public void accept(final Document document) {
            System.out.println(document.toJson());
        }
    };
    collection.find(gt("i", 50)).forEach(printBlock);
    // filter where; 50 < i <= 100
    collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock);
    // Sorting
    myDoc = collection.find(exists("i")).sort(descending("i")).first();
    System.out.println(myDoc.toJson());
    // Projection
    myDoc = collection.find().projection(excludeId()).first();
    System.out.println(myDoc.toJson());
    // Aggregation
    collection.aggregate(asList(match(gt("i", 0)), project(Document.parse("{ITimes10: {$multiply: ['$i', 10]}}")))).forEach(printBlock);
    myDoc = collection.aggregate(singletonList(group(null, sum("total", "$i")))).first();
    System.out.println(myDoc.toJson());
    // Update One
    collection.updateOne(eq("i", 10), set("i", 110));
    // Update Many
    UpdateResult updateResult = collection.updateMany(lt("i", 100), inc("i", 100));
    System.out.println(updateResult.getModifiedCount());
    // Delete One
    collection.deleteOne(eq("i", 110));
    // Delete Many
    DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
    System.out.println(deleteResult.getDeletedCount());
    // Create Index
    collection.createIndex(new Document("i", 1));
    // Clean up
    database.drop();
    // release resources
    mongoClient.close();
}
Also used : MongoClient(com.mongodb.client.MongoClient) Consumer(java.util.function.Consumer) ArrayList(java.util.ArrayList) Document(org.bson.Document) UpdateResult(com.mongodb.client.result.UpdateResult) DeleteResult(com.mongodb.client.result.DeleteResult) MongoDatabase(com.mongodb.client.MongoDatabase)

Example 14 with DeleteResult

use of com.mongodb.client.result.DeleteResult in project gora by apache.

the class MongoStore method deleteByQuery.

@Override
public long deleteByQuery(final Query<K, T> query) throws GoraException {
    try {
        // Build the actual MongoDB query
        Bson q = MongoDBQuery.toDBQuery(query);
        DeleteResult writeResult = mongoClientColl.deleteMany(q);
        return writeResult.getDeletedCount();
    } catch (Exception e) {
        throw new GoraException(e);
    }
}
Also used : GoraException(org.apache.gora.util.GoraException) DeleteResult(com.mongodb.client.result.DeleteResult) GoraException(org.apache.gora.util.GoraException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) Bson(org.bson.conversions.Bson)

Example 15 with DeleteResult

use of com.mongodb.client.result.DeleteResult in project spring-data-mongodb by spring-projects.

the class MongoTemplate method doRemove.

@SuppressWarnings("ConstantConditions")
protected <T> DeleteResult doRemove(String collectionName, Query query, @Nullable Class<T> entityClass, boolean multi) {
    Assert.notNull(query, "Query must not be null!");
    Assert.hasText(collectionName, "Collection name must not be null or empty!");
    MongoPersistentEntity<?> entity = getPersistentEntity(entityClass);
    DeleteContext deleteContext = multi ? queryOperations.deleteQueryContext(query) : queryOperations.deleteSingleContext(query);
    Document queryObject = deleteContext.getMappedQuery(entity);
    DeleteOptions options = deleteContext.getDeleteOptions(entityClass);
    MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.REMOVE, collectionName, entityClass, null, queryObject);
    WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
    return execute(collectionName, collection -> {
        maybeEmitEvent(new BeforeDeleteEvent<>(queryObject, entityClass, collectionName));
        Document removeQuery = queryObject;
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(String.format("Remove using query: %s in collection: %s.", serializeToJsonSafely(removeQuery), collectionName));
        }
        if (query.getLimit() > 0 || query.getSkip() > 0) {
            MongoCursor<Document> cursor = new QueryCursorPreparer(query, entityClass).prepare(// 
            collection.find(removeQuery).projection(MappedDocument.getIdOnlyProjection())).iterator();
            Set<Object> ids = new LinkedHashSet<>();
            while (cursor.hasNext()) {
                ids.add(MappedDocument.of(cursor.next()).getId());
            }
            removeQuery = MappedDocument.getIdIn(ids);
        }
        MongoCollection<Document> collectionToUse = writeConcernToUse != null ? collection.withWriteConcern(writeConcernToUse) : collection;
        DeleteResult result = multi ? collectionToUse.deleteMany(removeQuery, options) : collectionToUse.deleteOne(removeQuery, options);
        maybeEmitEvent(new AfterDeleteEvent<>(queryObject, entityClass, collectionName));
        return result;
    });
}
Also used : DeleteContext(org.springframework.data.mongodb.core.QueryOperations.DeleteContext) Document(org.bson.Document) WriteConcern(com.mongodb.WriteConcern) DeleteResult(com.mongodb.client.result.DeleteResult)

Aggregations

DeleteResult (com.mongodb.client.result.DeleteResult)46 Document (org.bson.Document)20 UpdateResult (com.mongodb.client.result.UpdateResult)10 BsonDocument (org.bson.BsonDocument)9 Test (org.junit.jupiter.api.Test)9 BasicDBObject (com.mongodb.BasicDBObject)7 WriteConcern (com.mongodb.WriteConcern)6 Bson (org.bson.conversions.Bson)6 MongoException (com.mongodb.MongoException)5 ArrayList (java.util.ArrayList)5 DataAccessException (org.springframework.dao.DataAccessException)5 MongoGridFSException (com.mongodb.MongoGridFSException)4 MongoClient (com.mongodb.client.MongoClient)4 OptimisticLockingFailureException (org.springframework.dao.OptimisticLockingFailureException)4 ReadPreference (com.mongodb.ReadPreference)3 MongoDatabase (com.mongodb.client.MongoDatabase)3 InsertOneResult (com.mongodb.client.result.InsertOneResult)3 MongoClient (com.mongodb.reactivestreams.client.MongoClient)3 MongoDatabase (com.mongodb.reactivestreams.client.MongoDatabase)3 ObjectId (org.bson.types.ObjectId)3