0

I want to create spring boot repository query using mongo db. I have collection name as qualification

{
    "code": "DEVELOPER",
    "description": "Software Developer",
    "status": "ACTIVE",
    "listItems": [
        {
            "itemId": "JAVA",
            "item": "Java"
        },
        {
            "itemId": "PYTHON",
            "item": "Python"
        },
        {
            "itemId": "PHP",
            "item": "Php"
        },
        {
            "itemId": "JAVASCRIPT",
            "item": "Javascript"
        }
    ],
    "returncode": "00000",
    "message": "Data Available"
}

I tried the below query to get whatever matches this pattern ja,

db.employee.aggregate([{$match:{"code" : "DEVELOPER"}},
{$project : {listItems:{$filter:{
    input: "$listItems",
               as: "listItems",
               cond: { $regexMatch:{
                        input:"$$listItems.item",
                        regex: /ja/i}  }
}}}}])

and i got exact answer as,

{
    "code": "DEVELOPER",
    "description": "Software Developer",
    "status": "ACTIVE",
    "listItems": [
        {
            "itemId": "JAVA",
            "item": "Java"
        },
        {
            "itemId": "JAVASCRIPT",
            "item": "Javascript"
        }
    ],
    "returncode": "00000",
    "message": "Data Available"
}

But when i tried in java using mongotemplate and got NULL pointer exception and didn't get any output

public List<ListValue> findAllByCode(String code,String item) {
           Query query = new Query();
           query.addCriteria(Criteria.where("code").is(code).and("listItems.item").regex("^" + item + "$", "i"));

           return mongoTemplate.find(query, ListValue.class);
        }
M N
  • 69
  • 2
  • 14
  • To run an Aggregation query as you are trying in `db.employee.aggregate([{$match:{"code" : "DEVELOPER"}}, ...`, you have to use the `MongoTemplate.aggregate` method (not the `find` method). – prasad_ May 09 '20 at 12:29
  • @prasad_ But there is no problem using find query which one OP tried.Have a look – Eklavya May 09 '20 at 12:50
  • @Eklavya The `find` query wont give the same result as that of the aggregate query. – prasad_ May 09 '20 at 13:43
  • @prasad_ I won't say about aggregate query I am saying find query is okay . – Eklavya May 09 '20 at 14:29
  • @prasad_ Can you help me to convert that **mongo native query** to **mongotemplate** aggregate query – M N May 09 '20 at 16:22
  • 1
    You can use the answer in this post as an example to use **springdata+mongodb** with **aggregate+project+filter**: [Create filter aggregation in spring](https://stackoverflow.com/questions/46767750/create-filter-aggregation-in-spring) To use **regex** use syntax like this: `Pattern p = Pattern.compile("ja", Pattern.CASE_INSENSITIVE); Criteria c = Criteria.where("someField").regex(p);` – prasad_ May 11 '20 at 01:56

0 Answers0