我无法通过在 MongoDB 中使用 Java 运算符使用
$addFields
作为 if else 条件来计算多个字段。我的要求是根据 if else 条件添加多个字段。我知道如何使用 $addFields
和 $project
添加多个字段,但不知道如何使用 if else 条件。
任何人都可以帮助我如何使用 MongoDB 运算符在 Java 中实现吗?
感谢任何帮助。预先感谢。
$addFields 语法:
.append(system, new Document()
.append("$cond", new Document()
.append("if", new Document()
.append("$eq", Arrays.asList(
"$system",
"AA"
)
)
)
.append("then", new Document()
.append("value.amount", new Document()
.append("$multiply", Arrays.asList(
"$value.amount",
Decimal128.parse("-1.0")
)
)
)
.append("value2", new Document()
.append("$multiply", Arrays.asList(
"$value.amount",
Decimal128.parse("-1.0")
)
)
)
)
$项目:
new Document()
.append("$project", new Document()
.append("_id", 0.0)
.append("value.amount", 0.0)
.append(sourceSystem, new Document(
"$cond", new Document(
"if", new Document("$eq", "true") )
)
.append("then", new Document()
.append("original.amount", 0.0)
.append("amount.amount", 0.0)
)
我们可以使用 $arrayToObject 运算符。
如果您评论管道步骤(从向后),您可以观察我们如何重塑文档。
db.collection.aggregate([
{
"$project": {
"tmp": {
$cond: [
{$eq: ["$system","AA"]},
[
[ "amount", { "$multiply": ["$value.amount",2.0]}],
[ "field1", "$value.field1"],
[ "field2", "$value.field2"],
[ "field3", "$value.field3"]
],
[
[ "amount", { "$multiply": ["$amount.amount",-2.0]}],
[ "field1", "$amount.field3"],
[ "field2", "$amount.field2"],
[ "field3", "$amount.field1"]
]
]
}
}
},
{
$addFields: { tmp2: {"$arrayToObject": "$tmp"}}
},
{
"$replaceWith": "$tmp2"
}
])