2

I have to create a service which takes a list of text and searches for matches in an embedded array in documents in MongoDB. For example, I have to search this list of text:

["Tom", "Keanu", "Arnold"]

in the following collections:

[{id: "123", title: "Movie 1", cast: [{id: 1, name: "Tom Hanks"}, {id: 2, name: "Actor 2"}]}, 
{id: "123", title: "Movie 1", cast: [{id: 1, name: "Keanu Reeves"}, {id: 2, name: "Actor 2"}]}
{id: "123", title: "Movie 1", cast: [{id: 1, name: "Arnold Schwarzenegger"}, {id: 2, name: "Actor 2"}]}]

Searching above text should return these three movies. It requires me to create a query like below:

db.movies.find({cast.name: {$in: [/Tom/, /Keanu/, /Arnold/]}})

This is because according to official doc, we cannot use $regex with $in. However I am not able to find a way to translate this into Spring Data Mongo query.

This Stackoverflow thread explains how to search for a single text in an embedded array using regex but I couldn't find anything about searching from a given list in an embedded document using Spring data Mongo. Any help would be greatly appreciated.

1 Answer 1

3

You should be able to do this using $elemMatch and regex criteria. $elemMatch equivalent in spring data mongodb has a good discussion of $elemMatch in spring data. Something like:

Criteria.where("cast").elemMatch(Criteria.where("name").regex("Tom|Keanu|Arnold"));
Sign up to request clarification or add additional context in comments.

1 Comment

It worked! Thanks, marking this as the correct answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.