Using conditional operator in a spring mongo [duplicate]

99封情书 提交于 2019-12-02 09:08:44

You are using the (CriteriaDefinition) api (not sure why is this exposed in projection, may be because aggregation operators does share some of its functions with query operators ) to generate the conditional expression, which should be used for regular query expressions( used in $match stage and regular find queries).

The criteria definition api generates the following query.

"isMatchingRoles": {
    "$cond": {
        "if": {
            "$eq": ["$organization.roles.orgRoleId", "userOrgMap.roleId"]
        },
        "then": true,
        "else": false
    }
} 

Notice the second argument to the $eq is string value rather than field reference.

You can do it in following two ways.

Using ConditonalOperator api.

.and(when(ComparisonOperators.Eq.valueOf("organization.roles.orgRoleId").equalTo("userOrgMap.roleId")).then(true).otherwise(false)).as("isMatchingRoles")

Use AggregationExpression to generate the conditional expression.

and(new AggregationExpression() {
            @Override
            public DBObject toDbObject(AggregationOperationContext context) {
                return new BasicDBObject("$cond",
                        Arrays.<Object>asList(
                                new BasicDBObject("$eq", 
                                        Arrays.asList("$organization.roles.orgRoleId", "$userOrgMap.roleId")),
                                true,
                                false));
            }
 }).as("isMatchingRoles");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!