只需 Documents 和 Lists
List<Document> pipeline = Arrays.asList(
new Document("$project",
new Document("data1", 1)
.append("result", new Document(
"$cond", new Document(
"if", new Document("$eq", Arrays.asList("$salary", 250000) )
)
.append("then", 30)
.append("else", 20)
))
)
);
序列化为:
[
{ "$project": {
"data1": 1,
"result": {
"$cond": {
"if": { "$eq": [ "$salary", 250000 ] },
"then": 30,
"else": 20
}
}
}}
]
或者交替使用$cond的“列表”形式:
List<Document> pipeline = Arrays.asList(
new Document("$project",
new Document("data1", 1)
.append("result", new Document(
"$cond", Arrays.asList(
new Document("$eq", Arrays.asList("$salary", 250000) ),
30,
20
)
))
)
);
序列化为:
[
{ "$project": {
"data1": 1,
"result": {
"$cond": [
{ "$eq": [ "$salary", 250000 ] },
30,
20
}
}
}}
]
两者都是$cond 的有效用法。
还要注意您的问题中的错误,您可能是指 $eq 或者您可能是指 $gt 或条件上的其他逻辑运算符。 $cond 期望“如果”返回一个布尔值。
根据驱动程序,您可以将 Document 替换为 BasicDBObject。