How to update a field in MongoDB using Java driver with the value of another field in the collection?

I am using MongoDB with Java driver. I am trying to update a field by multiplying another with a number and setting it. But instead of the result of the multiplication, the field is being set by a BasicDBObject. How do I make it so that the result is set?

Please give the answer using the Update builders of the Java driver?

    Bson filter1 = and(
            eq("platform", platform),
            eq("channel", channel)
    );
    double percent = 20;
    final Bson update = set("percent_view", new BasicDBObject("$multiply", Arrays.asList("$viewtime", percent)));

    collection.updateOne(filter1, update);

Hi @khat33b and welcome to MongoDB community forums!!

If I understand your question correctly you have the sample document that looks like:

Atlas atlas-b8d6l3-shard-0 [primary] test> db.testMultiply.find()
[
  {
    _id: ObjectId("64f6db5af8128204652e1551"),
    platform: 'platform',
    channel: 'channel',
    view: 50
  }
]

and you are trying to update the field value percent_view as view * 20.

Could you please explain why you want to limit the use of Update builder operators?

It’s more straightforward to achieve this with the aggregation pipeline. You can check the code below to see how it’s done using the aggregation pipeline:

import java.util.Arrays;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.conversions.Bson;
import java.util.concurrent.TimeUnit;
import org.bson.Document;
import com.mongodb.client.AggregateIterable;

MongoClient mongoClient = new MongoClient(
    new MongoClientURI(
        ""
    )
);
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("testMultiply");

AggregateIterable<Document> result = collection.aggregate(Arrays.asList(new Document("$match", 
    new Document("channel", "channel")
            .append("platform", "platform")), 
    new Document("$addFields", 
    new Document("percent_view", 
    new Document("$multiply", Arrays.asList("$view", 20L))))));

If you prefer to continue using the update builders, one potential solution is to extract the field value at the application end, carry out the mathematical operation, and then use $set to assign the calculated value.

Please let us know if you need further help.

Regards
Aasawari

2 Likes