Reputation: 69
I nedded to implement 'if condition'in java i don't know how to do that,So give some suggestion to that
db.test.aggregate(
[
{
$project:
{
data: 1,
result:
{
$cond: { if: { $cond: [ "$salary", 250000 ] }, then: 30, else: 20 }
}
}
}
]
)
Upvotes: 0
Views: 3245
Reputation: 151112
Just Documents
and List
s
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)
))
)
);
Serializes as:
[
{ "$project": {
"data1": 1,
"result": {
"$cond": {
"if": { "$eq": [ "$salary", 250000 ] },
"then": 30,
"else": 20
}
}
}}
]
Or alternately using the "list" form of $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
)
))
)
);
Serializes as:
[
{ "$project": {
"data1": 1,
"result": {
"$cond": [
{ "$eq": [ "$salary", 250000 ] },
30,
20
}
}
}}
]
Both are valid usages of $cond
.
Also noting the error in your question, you might mean $eq
or you might mean $gt
or other logical operator on the condition. $cond
expects it's "if" to return a boolean.
Depending on the driver you might interchange Document
with BasicDBObject
instead.
Upvotes: 2