Example usage for com.mongodb.client MongoCollection replaceOne

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

Introduction

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

Prototype

UpdateResult replaceOne(Bson filter, TDocument replacement);

Source Link

Document

Replace a document in the collection according to the specified arguments.

Usage

From source file:net.netzgut.integral.mongo.internal.services.MongoODMImplementation.java

License:Apache License

@Override
public <T extends Serializable> UpdateResult replace(Bson filter, T entity) {
    Class<? extends Serializable> entityClass = entity.getClass();
    MongoCollection<Document> collection = this.mongo.getCollection(entityClass);
    Document replacement = this.converter.documentFrom(entity);
    return collection.replaceOne(filter, replacement);
}

From source file:net.springfieldusa.storage.mongodb.comp.MongoStorageComponent.java

License:Open Source License

@Override
public <T extends EntityObject> long update(String collection, T data) {
    MongoCollection<Document> mongoCollection = getCollection(collection);
    Document document = new Document(data.getAttributes());
    document.put(ID, data.getId());/*from  ww w.j a  va  2s .  co m*/
    document.put(META, data.getMeta());
    document.put(RELATIONSHIPS, createRelationships(data));
    UpdateResult result = mongoCollection.replaceOne(eq(ID, data.getId()), document);
    return result.getMatchedCount();
}

From source file:nl.mvdb.mongodb.RemoveStudentsLowestHomeworkScore.java

License:Apache License

public static void main(String[] args) {
    MongoClient client = new MongoClient();
    try {/*  ww  w . j a v a2s  .  c om*/
        MongoDatabase database = client.getDatabase("school");
        MongoCollection<Document> collection = database.getCollection("students");

        MongoCursor<Document> iterator = collection.find().sort(ascending("scores.score")).iterator();

        while (iterator.hasNext()) {
            Document studentDoc = iterator.next();
            System.out.println(studentDoc);

            Document lowestScoreDoc = null;

            List<Document> scoreDocs = (ArrayList) studentDoc.get("scores");
            for (Document scoreDoc : scoreDocs) {
                if ("homework".equals(scoreDoc.getString("type"))) {
                    Double score = scoreDoc.getDouble("score");
                    if (lowestScoreDoc == null || score < lowestScoreDoc.getDouble("score")) {
                        lowestScoreDoc = scoreDoc;
                    }
                }
            }

            if (lowestScoreDoc != null) {
                scoreDocs.remove(lowestScoreDoc);
                studentDoc.put("scores", scoreDocs);
                collection.replaceOne(new Document("_id", studentDoc.getInteger("_id")), studentDoc);
            }

        }

        System.out.println(collection.count());
    } finally {
        client.close();
    }
}

From source file:org.bananaforscale.cormac.dao.document.DocumentDataServiceImpl.java

License:Apache License

/**
 * Updates a document in the collection. If the document exists in the
 * collection it will be updated. If the document doesn't exist an error
 * will be thrown. If the specified database and collection do not exist
 * they will be created./*from  ww  w  .j  av  a 2 s  .  c  o m*/
 *
 * @param databaseName the database
 * @param collectionName the collection
 * @param documentId the document identifier
 * @param content the JSON payload
 * @return a status message with the outcome of the operation
 * @throws DatasourceException
 * @throws DeserializeException
 * @throws IllegalArgumentException
 * @throws NotFoundException
 */
@Override
public boolean replaceById(String databaseName, String collectionName, String documentId, String content)
        throws DatasourceException, DeserializeException, IllegalArgumentException, NotFoundException {
    try {
        if (!validInputForAddOrUpdate(databaseName, collectionName, documentId, content)) {
            throw new IllegalArgumentException();
        }
        MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);
        MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName);
        Document query = new Document("_id", new ObjectId(documentId));
        Document document = Document.parse(content);
        if (collection.count(query) == 0) {
            throw new NotFoundException("The document doesn't exist in the collection");
        }
        collection.replaceOne(query, document);
        return true;
    } catch (IllegalArgumentException | ClassCastException | JSONParseException ex) {
        logger.error("The JSON payload is invalid", ex);
        throw new DeserializeException("The JSON payload is invalid");
    } catch (MongoException ex) {
        logger.error("An error occured while updating the document", ex);
        throw new DatasourceException("An error occured while updating the document");
    }
}

From source file:org.codinjutsu.tools.nosql.mongo.logic.SingleMongoClient.java

License:Apache License

public void update(ServerConfiguration configuration, SingleMongoCollection singleMongoCollection,
        Document mongoDocument) {
    MongoClient mongo = null;//from ww  w .  j av a 2  s.com
    try {
        String databaseName = singleMongoCollection.getDatabaseName();
        mongo = createMongoClient(configuration);

        MongoDatabase database = mongo.getDatabase(databaseName);
        MongoCollection<Document> collection = database.getCollection(singleMongoCollection.getName());

        final Object id = mongoDocument.get("_id");
        if (id == null) {
            collection.insertOne(mongoDocument);
        } else {
            collection.replaceOne(Filters.eq("_id", id), mongoDocument);
        }
    } catch (UnknownHostException ex) {
        throw new ConfigurationException(ex);
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }
}

From source file:org.netbeans.modules.mongodb.ui.components.result_panel.actions.EditBsonPropertyNodeAction.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent e) {
    BsonProperty property = propertyNode.getBsonProperty();
    BsonProperty newProperty = BsonPropertyEditor.show(property);
    if (newProperty == null) {
        return;//from   w ww. ja  v a 2 s .  c om
    }
    propertyNode.setPropertyName(newProperty.getName());
    getResultPanel().getTreeTableModel().setUserObject(propertyNode, newProperty.getValue());
    TreeTableNode parentNode = propertyNode.getParent();
    BsonDocument document = (BsonDocument) parentNode.getUserObject();
    if (newProperty.getName().equals(property.getName()) == false) {
        document.remove(property.getName());
    }
    document.put(newProperty.getName(), newProperty.getValue());
    while ((parentNode.getParent() instanceof RootNode) == false) {
        parentNode = parentNode.getParent();
    }
    try {
        final MongoCollection<BsonDocument> collection = getResultPanel().getLookup()
                .lookup(MongoCollection.class);
        collection.replaceOne(Filters.eq("_id", document.get("_id")), document);

    } catch (MongoException ex) {
        DialogNotification.error(ex);
    }
}

From source file:org.netbeans.modules.mongodb.ui.components.result_panel.actions.EditBsonValueNodeAction.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent e) {
    BsonValue value = valueNode.getValue();
    BsonValue newValue = BsonPropertyEditor.show("value", value);
    if (newValue == null || newValue.equals(value)) {
        return;/* w w w. j  a va  2s.c  o  m*/
    }
    getResultPanel().getTreeTableModel().setUserObject(valueNode, newValue);
    TreeTableNode parentNode = valueNode.getParent();
    BsonArray array = ((BsonValueNode) parentNode).getValue().asArray();
    int index = array.indexOf(value);
    array.set(index, newValue);
    while ((parentNode.getParent() instanceof RootNode) == false) {
        parentNode = parentNode.getParent();
    }
    try {
        MongoCollection<BsonDocument> collection = getResultPanel().getLookup().lookup(MongoCollection.class);
        BsonDocument document = (BsonDocument) parentNode.getUserObject();
        collection.replaceOne(eq("_id", document.get("_id")), document);
    } catch (MongoException ex) {
        DialogNotification.error(ex);
    }
}

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
 *//*from   w  w  w.ja v  a  2  s  .  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();
}