Reputation: 153
I have a collection of movies structured with title, writers, rated, actors and others fields.
I am trying to find movies with at least one actors with name and lastname starting with a C and show the title and the actors. Actors is an array with actors (first name then last name on the same field) for example: {Matt Damon, Bradd Pitt} etc...
I tried with this :
db.movieDetails.find(
{ actors: { $regex: "^C.C" , $options: 'i' } },
{_id:0, title:1, actors:1}
);
and also with aggregation like this :
db.movieDetails.aggregate(
{$unwind: '$actors'},
{$match: { actors: { $regex: "^C.C", $options: 'i' } } },
{$group: {_id: { actors: '$actors' , title: "$title" }}}
);
But I'm just trying to avoid the problem by looking when there is an actor starting with C and another occurrence, and this solution works only partially because it returns me movies with two actors with only their first name starting with a C.
I would like to know if there is a way to use regex for example to check all words starting with something in the whole string.
Upvotes: 0
Views: 222
Reputation: 20805
The regex that you have provided is incorrect. An explanation of ^C.C
Basically, it will match any actor name where the 1st and 3rd letter are C.
Instead, try this regex: ^C.* C
. Explanation:
Mongo code:
db.movieDetails.find({
actors: {
$regex: "^C.* C",
$options: "i"
}
});
Upvotes: 2