英文:
MongoDB Java Driver: How to use $cond operator?
问题
我已经编写了以下的MongoDB更新查询:
db.getCollection("product").update(
{},
[
{
$set: {
availability: {
$cond: [
{
$eq: ["$availability", true],
},
"Yes",
"No",
],
},
},
}
]
);
这个查询会更新product
集合中的所有文档:根据当前值设置availability
属性的新值。
而我正在尝试使用MongoDB Java驱动程序重写上面的查询:
db.getCollection("product")
.updateMany(new BsonDocument(), Updates.set("available", "YES"));
但是我卡在了$cond
操作符上,我不知道如何将MongoDB查询中的$cond
操作符翻译成Java驱动程序。
您能否提供可能的选项?
英文:
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?
答案1
得分: 2
需要使用不同的变体,需要使用 ClientSession
而不是 MongoClient
UpdateResult updateResult = this.mongoColWrite.
updateMany(this.clientSession, new Document(), setUpdateList);
空文档
是条件。你可以在那里添加任何条件。
你必须提供更新的列表。
[
{
$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);
这是我通常的做法。每个数组都是一个 list
。每个对象都是一个 Document
。
英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论