0

I am looking for a way to update a document replacing a substring of a field with another value.
For example, in my database i have the following field:

{
    "_id": 1,
    "value": "Old text in the document"
}

To update the field i would simply do somehting like this

        MongoClient client = ...init client mongodb
        try (ClientSession session = MongoSession.createSession(client)) {
            session.startTransaction(TransactionOptions.builder().writeConcern(WriteConcern.MAJORITY).build());
            MongoDatabase database = client.getDatabase("test_db");

            MongoCollection<FileEntity> filesDB = database.getCollection("my_collection", MyClass.class);
            Bson query = Filters.and(Filters.eq("_id", 1));
            Bson updates = Updates.set("value", "New text in the document");

            filesDB.updateOne(session, query, updates);
            session.commitTransaction();
        } catch (Exception e) {
            logger.error("Error: ", e);
        } finally {
            logger.debug("Success");
        }

And this would result in:

{
    "_id": 1,
    "value": "New text in the document"
}

But this would require that i know the current value of the field, but in my case i don't.
So i am trying to find a way to say something like

Bson updates = Updates.set("value", "$value.replace(\"Old\", \"New\")");

Is this possible?
The java driver of mongodb i have is version 3.12.10 and my mongodb server version is v4.2.12.
Thanks!

3
  • 1
    If you have 4.4+, you can use $replaceOne or $replaceAll Commented May 18, 2022 at 14:43
  • 1
    But how do i do it in java, could you explain any further please? Commented May 18, 2022 at 14:47
  • Refer this Commented May 18, 2022 at 14:52

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.