regex - How to find all documents having an identical values in two fields with MongoDB? -
given new documents , querys: { "_id" : objectid("55803fd1cc0c9aa090e608be"), "song_name" : "mickey good", "time" : "3.56", "artist" : "mickey" } { "_id" : objectid("55803fd1cc0c9aa090e608bf"), "song_name" : "love nothing", "time" : "5.56", "artist" : "jimmy" }
i need find songs have title identical artist name. have tried: db.mycollection.find( { $where: "this.artist == /this.song_name/" } );
but did not work out. please help`
if understand well, need find songs title contains name of artist. don't need regular expression that1. simple test using indexof
suffice. given sample data:
> db.test.find({$where: "this.song_name.tolowercase().indexof(this.artist.tolowercase()) > -1" }) { "_id" : objectid("557ccec684ee2ba0375f4fcf"), "song_name" : "mickey good", "time" : "3.56", "artist" : "mickey" }
if need find songs title is equal artist name (you don't have such document in sample data), 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 strings using tolowercase()
. depending use case, might need more sophisticated that. example, if need match "you , me" "you+me".
1using regular expression here might harmful if artist name contains meta-characters or quantifiers. example, given artist name "you+me", +
here interpreted 1 or more occurrence of preceding character. so, matching "youme", "youuuuume" but not raw string "you+me".
Comments
Post a Comment