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.