If I understand it well, you need to find all songs whose title contains the name of the artist. You don't need a regular expression for that1. As simple test using indexOf
would suffice. Given your sample data:
> db.test.find({$where:
"this.song_name.toLowerCase().indexOf(this.artist.toLowerCase()) > -1"
})
{ "_id" : ObjectId("557ccec684ee2ba0375f4fcf"),
"song_name" : "Mickey is good",
"time" : "3.56",
"artist" : "Mickey" }
If you really need to find the songs whose title is equal to the artist name (you don't have such a document in your sample data), you would simply write:
> db.test.find({$where:
"this.song_name.toLowerCase() == this.artist.toLowerCase()"
})
{ "_id" : ObjectId("557cd12284ee2ba0375f4fd1"),
"song_name" : "The Monkeys",
"artist" : "The Monkeys" }
Please note in either cases, I've normalized the strings using toLowerCase()
. Depending your use case, you might need something much more sophisticated than that. For example, if you need to match "You and Me" by "You+Me".
1Using a regular expression here might even be harmful if the artist name contains meta-characters or quantifiers. For example, given the artist name "You+Me", the +
here would be interpreted as 1 or more occurrence of the preceding character. So, matching "YouMe", "YouuuuuMe" but not the raw string "You+Me".