MongoDB Query to Criteria MongoDB conversion throwing exception

Viewed 40

I got a Mongo query like this:

{$and:
[
      {$or:
      [
           {"itemNbr": { $in: :#{#itemNbrs} }},
           {"deptNbr": { $in: :#{#deptNbrs} }} //I haven't provided the criteria code bellow.
      ]},
      {"allocationPlanType": :#{#allocationPlanType}},
      {$or:
      [
           {"overallNeedQuantity": { $gte: :#{#showAllocationPlan} }},
           {"overallPlannerQuantity": { $gte: :#{#showAllocationPlan} }}
      ]}
      {$or:
      [
           {"itemDesc1": { $eq: :#{#itemName} }},
           {"itemDesc2": { $gte: :#{#itemName} }}
      ]}
]}

I have written a criteria query like this:

List<Criteria> andExpression = new ArrayList<>();
if (!CollectionUtils.isEmpty(itemNbrs)) {
            itemNbrQuery = Criteria.where("itemNbr").in(itemNbrs);
            andExpression.add(itemNbrQuery);
        }

 andExpression.add(Criteria.where("allocationPlanType").is(allocationPlanType));
    if(Objects.nonNull(itemName))
    {
        itemNameQuery=criteria.orOperator(
                Criteria.where("itemDesc1").is(itemName),
                Criteria.where("itemDesc2").is(itemName)
        );

        andExpression.add(itemNameQuery);
    }
  if (Objects.isNull(choice)) {
            Criteria noFltersQuery = criteria.orOperator(
                    Criteria.where("overallNeedQuantity").gte(showAllocationPlan),
                    Criteria.where("overallPlannerQuantity").gte(showAllocationPlan)
            );
            andExpression.add(noFltersQuery);
            
    }else {
        Criteria noFltersQuery = 
        Criteria.where("overallPlannerQuantity").gte(showAllocationPlan);
        andExpression.add(noFltersQuery);
    }
    query.with(pageableRequest);
    query.addCriteria(criteria.andOperator(andExpression.toArray(new Criteria[andExpression.size()])));

Now its throwing this exception :

Due to limitations of the org.bson.Document, you can't add a second '$or' expression specified as '$or : [Document{{overallNeedQuantity=Document{{$gte=1}}}}, Document{{overallPlannerQuantity=Document{{$gte=1}}}}]'. Criteria already contains '$or : [Document{{itemDesc1=COMP CURR PREK WORKBOOK}}, Document{{itemDesc2=COMP CURR PREK WORKBOOK}}]'.

Now I know this exception is very common in MongoDB but I am not getting clue how to construct the Criteria query as per my need to avoid this exception.

0 Answers
Related