[英]MongoDB Java Driver: How to use $cond operator?
I've written the following MongoDB update query:我编写了以下 MongoDB 更新查询:
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.更新product
集合中的所有文档:根据当前值设置availability
属性的新值。
And I am trying to rewrite the query above for MongoDB Java driver:我正在尝试为 MongoDB Java 驱动程序重写上面的查询:
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.但我坚持使用$cond
运算符,我不知道如何将$cond
运算符从 MongoDB 查询转换为 Java 驱动程序。
Could you please suggest possible options?你能建议可能的选择吗?
You need to use different variation which requires ClientSession
rather than MongoClient
您需要使用需要ClientSession
而不是MongoClient
的不同变体
UpdateResult updateResult = this.mongoColWrite.
updateMany(this.clientSession, new Document(), setUpdateList);
empty doc
is the condition. empty doc
是条件。 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
.每个数组都是一个list
。 Every object is a Document
.每个 object 都是一个Document
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.