in this app I'm doing I also inserted a feature that allows me to look for specific items inside my objects of my Database repositories. For that, I used mongo template. Every object in my repository gets compounded of the following items:
[
{
"id": "5f759b198dfb247ccd6280b2",
"name": "Probando lo que cree",
"text": "Enrique Gordon",
"description": "Un poquito de todo ",
"images": [
"R0lGODlhLAEsAff"
],
"videos": [
"AAAAIGZ0eXBpc29"
],
"date": null,
"allComments": null
},
{
"id": "5f759d2b8dfb247ccd6280ba",
"name": "Probando lo que cree",
"text": "Enrique Gordon",
"description": "Algo nuevo",
"images": [
"R0lGODlhLAEsAff"
],
"videos": [
"AAAAIGZ0eXBpc29"
],
"date": null,
"allComments": null
},
{
"id": "5f75a5e2275d7d34914d2d98",
"name": "Zamorano",
"text": "Zamorano",
"description": "Zamorano",
"images": [
"iVBORw0KGgoAAAA",
"/9j/4T/+RXhpZgA"
],
"videos": [
"AAAAIGZ0eXBpc29"
],
"date": null,
"allComments": null
}
]
Thus having this in mind I initialized in my repository a function which returns a query bearing with the items : description, text, and name
REPOSITORY
public List<Post> searchPosts(String search){
return mongoTemplate.aggregate(Aggregation.newAggregation(
Aggregation.match(new Criteria().orOperator(
Criteria.where("text").regex(search),
Criteria.where("description").regex(search),
Criteria.where("name").regex(search),
))
),"Post",Post.class).getMappedResults();
}
*The post is the class already initialized with getters and setters, having in mind the concepts text, name , and description too
Then on my end point having in mind that criteria I pass whatever it brings as a path variable to my end point
CONTROLLER
@GetMapping("/post/{search}/search")
public List<Post> getSearchedPosts(@PathVariable ("search") String search){
return postRepository.searchPosts(search);
}
But for any reason when I bring to test the process in the postman, it brings me all the objects, but not the queried one.
Am I omitting something in the java query function?
You won't need aggregation for this.
Try this - Hope this would work.
I have tried this on my local env with the sample documents you provided. I used
Zamorano
as search string. I am getting only one result. Here is my code -And this is img from postman -
PS - Make sure your imports are correct.