1

How do I execute different updates on different fields of a single document as a single operation using java driver? Suppose I have a document like this

{
   _id: ObjectId("1234567890")
   ...
   elements: String[],
   last_user: String,
   ...
}

and I want to add a string to the elements array and update last_user. I can do it as

import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Updates.*;

...

Bson filter = eq(DBCollection.ID_FIELD_NAME, new ObjectId("1234567890"));
Bson addElement = push("elements", "a new string");
Bson updateLastUser = set("last_user", "last user name");

mycollection.updateOne(filter, addElement);
mycollection.updateOne(filter, updateLastUser);

it works but those are two separate operations, and I don't actually like it at all.

I saw in this question that with the shell i can do it like this

db.mycollection.update({ "_id": "1234567890" }, 
   {
      "$push" : { "elements": "a new string" }, 
      "$set" : { "last_user": "last user name" }
   }
);

but I have no idea how I can build that single update object containing both $push and $set with java driver . I'm quite sure it's pretty simple and stupid but I can't find a solution.

1 Answer 1

1

Use combine.

mycollection.updateOne(filter, combine(addElement,updateLastUser);
Sign up to request clarification or add additional context in comments.

Comments

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.