1

I want to convert this query to a java code with Aggregation and criteria using $unwind to get individual document and $project to get a personalized response.

db.getCollection('WarrantyCategory').aggregate([{
    $unwind: '$subWarrantyCategories'
},
{
    $match: {
        $and: [{
                $and: [{
                        'subWarrantyCategories.filtersAllowed.type._id': 'CODE_ACTE'},
                    {
                        $and: [{'subWarrantyCategories.filtersAllowed.valuesAutorized.id': 'ORT'}, 
                               {'subWarrantyCategories.filtersAllowed.valuesAutorized.operator': '='}]

                    }
                ]
            },
            {

                $and: [{'subWarrantyCategories.filtersAllowed.type._id': 'TYP_ACCORD'},

                    {
                        $and: [{'subWarrantyCategories.filtersAllowed.valuesAutorized.id': 'O'},{'subWarrantyCategories.filtersAllowed.valuesAutorized.operator': '='}]

                    }]
            }
        ]
    }
},
{
    $project: {

        _id: 0,

        label: 1,

        code: 1,

        labelSCat: '$subWarrantyCategories.label',

        CodeSCat: '$subWarrantyCategories._id'}}])

I tried an example with @Query but without $unwind and it worked very well

Chedy
  • 57
  • 1
  • 4
  • Please post the Java code you had tried, and tell what is not working in it (or what is the difficult part in it). – prasad_ Dec 24 '19 at 05:13

1 Answers1

2

Sample code for spring data mongodb

List<AggregationOperation> stages = new ArrayList<>();

stages.add(unwind("$subWarrantyCategories"));

List<Criteria> andList = new ArrayList<>();

Criteria c1 = new Criteria("subWarrantyCategories.filtersAllowed.type._id").is("CODE_ACTE");
Criteria c2  new Criteria("subWarrantyCategories.filtersAllowed.valuesAutorized.id").is("ORT");
Criteria c3 =  new Criteria("subWarrantyCategories.filtersAllowed.valuesAutorized.operator").is("=");
Criteria c4  new Criteria("subWarrantyCategories.filtersAllowed.type._id").is("TYP_ACCORD");
Criteria c5 =  new Criteria("subWarrantyCategories.filtersAllowed.valuesAutorized.id").is("0");
Criteria c5 =  new Criteria("subWarrantyCategories.filtersAllowed.valuesAutorized.operator").is("=");


andList.add(new Criteria().andOperator(c1, new Criteria().andOperator(c2,c3)));
andList.add(new Criteria().andOperator(c4, new Criteria().andOperator(c5,c6)));

stages.add(match(new Criteria().andOperator(andList.toArray(new Criteria[andList.size()]))));

ProjectionOperation projection = project("_id", "label",  "code").and("$subWarrantyCategories.label").as("labelSCat").and("$subWarrantyCategories._id").as("CodeSCat");

stages.add(projection);

newAggregation(stages)
Ashish Bakwad
  • 791
  • 4
  • 15