Raphael Lopes
Raphael Lopes

Reputation: 153

Occurance of two words with specific initials MongoDB

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

Answers (1)

asemahle
asemahle

Reputation: 20805

The regex that you have provided is incorrect. An explanation of ^C.C

  • ^ - Matches the start of a line
  • C - Matches the character C
  • . - Matches any single character
  • C - Matches the character C

Basically, it will match any actor name where the 1st and 3rd letter are C.

Instead, try this regex: ^C.* C. Explanation:

  • ^ - Matches the start of a line
  • C - Matches the character C
  • .* - Matches any character between zero and unlimited times
  • (space)C - Matches a space followed by a C (this assumes the last name is separated from the first name by a space)

Mongo code:

db.movieDetails.find({
  actors: {
    $regex: "^C.* C",
    $options: "i"
  }
});

Upvotes: 2

Related Questions