I've written the following MongoDB update query:
db.getCollection("product").update(
{},
[
{
$set: {
availability: {
$cond: [
{
$eq: ["$availability", true],
},
"Yes",
"No",
],
},
},
}
]
);
that updates all documents in product
collection: set a new value for availability
property based on its current value.
And I am trying to rewrite the query above for MongoDB Java driver:
db.getCollection("product")
.updateMany(new BsonDocument(), Updates.set("available", "YES"));
but I am stuck with $cond
operator, I don't know how to translate $cond
operator from MongoDB query to Java driver.
Could you please suggest possible options?
You need to use different variation which requires ClientSession
rather than MongoClient
UpdateResult updateResult = this.mongoColWrite.
updateMany(this.clientSession, new Document(), setUpdateList);
empty doc
is the condition. You can add any condition there.
You have to provide the list for the update.
[
{
$set: {
availability: {
$cond: [
{
$eq: ["$availability", true],
},
"Yes",
"No",
],
},
},
}
]
LinkedList<Object> condList = new LinkedList<Object>();
LinkedList<Object> eqArray = new LinkedList<Object>();
eqArray.add("$availability");
eqArray.add(true);
condList.add(new Document("$eq"), eqArray);
condList.add("Yes");
condList.add("No");
Document availDoc = new Document("$cond", condList)
Document setDoc = new Document("$set", availDoc);
LinkedList<Document> setUpdateList = new LinkedList<Document>();
setUpdateList.add(setDoc);
This is how I usually does. Every array is a list
. Every object is a Document
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.