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!