Using Micronaut data to perform the below operations
- Find the item with id and subcategory id
- Update the subcategory item based on category id and sub-category id
- Delete the subcategory item based on category id and sub category id
I have the below data structure
{
"id": "625a8d1a23c8feb3234fbf28",
"name": "Category 1",
"description": "Category 1 description",
"subCategory": [{
"id": "625a8d6fe0e3cff6e8a3b795",
"name": "Sub Category 1",
"description": "Sub Category 1 description"
},
{
"id": "625a8d782672979b1482f5ca",
"name": "Sub Category 2",
"description": "Sub Category 2 description"
}
]
}
There is a custom query builder in micronaut as describe here https://micronaut-projects.github.io/micronaut-data/latest/guide/#mongoCustomQueries and https://micronaut-projects.github.io/micronaut-data/latest/guide/#mongoCriteriaExecuteQuery
@Introspected
public record SubCategorySpecification() {
public static PredicateSpecification<Category> categoryAndSubCategoryIdEquals(ObjectId categoryId, ObjectId subCategoryId) {
return (root,criteriaBuilder) -> {
criteriaBuilder.equal(root.get("id"), categoryId);
return criteriaBuilder.and(criteriaBuilder.equal(root.get("subCategory.id"), subCategoryId));
};
}
}
I tried the above code and got an exception as Cannot query entity [Category] on non-existent property: subCategory.id
and not sure how to write the custom query using @ MongoFindQuery
You might need to have the subcategory defined as embedded to be properly recognized.
It's possible to define a custom query:
In a similar way, you can use
@MongoUpdateQuery
and@MongoDeleteQuery
. For the syntax check official MongoDB documentation.