2017-07-17 10 views
0

mongodbのregex findは検索よりもフィルターのように機能します。とにかく正規表現に基づいて結果を並べ替えるには?regex sorting mongodb mongooseを見つけよう

P.S:MongoDBには全文検索がありますが、部分的な単語が入力されても結果を返すソリューションを探しています。

また、私はMongoDBとElastic Searchを接続するなどのソリューションがあることを知っていますが、別のサービスをホストする必要のないシンプルなソリューションを探しています。

また、パフォーマンスは問題ではありません。

+3

「正規表現に基づいて結果を並べ替える」とはどういう意味ですか?特定の例を含めるように質問を更新すると非常に役に立ちます。 – JohnnyHK

答えて

0

$の正規表現は、フィールドタイプString.Itのためだけに使用され

以下のようにユーザーモデルを見てみましょう//正規表現演算子で

を再生するための小さな例を考えてみましょう他の種類

では動作しません。

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 
var UserSchema = new Schema({ 
    Name:String, 
    Age:Number, 
    Sex:Boolean, 
    EmailID:String, 
    PhoneNumber:String, 
    Description:String, 
    created_at:Date, 
    updated_at:Date 
}); 
module.exports = mongoose.model('UserSchema', UserSchema); 

マルチ$の正規表現演算子による検索やマルチ検索のための$オプションのためのあなたのMongoDBのクエリは次のようになりますよう

var toSearch = req.body.searchvalue; 
var query = { 
    $or:[ 
     { 
      "Name":{ 
       $regex:toSearch, 
       $options:"i"  //it will match both upper case and lower case 
      } 
     }, 
     { 
      "EmailID":{ 
       $regex:toSearch, 
       $options:"i"  //it will match both upper case and lower case 
      } 
     }, 
     { 
      "PhoneNumber":{ 
       $regex:toSearch, 
       $options:"i"  //it will match both upper case and lower case 
      } 
     },{ 
      "Description":{ 
       $regex:toSearch, 
       $options:"i"  //it will match both upper case and lower case 
      } 
     } 
    ] 
} 
//Important point to remember we cannot use $regex for age,sex,created_at,updated_at because this field are not String 


UserSchema.find(query).toArray(function (err,SearchData) { 
    if(!err){ 
     //perform your operations 
    } 
}) ; 
以下0

これはあなたを助けるかもしれませんが、mongodbで検索エンジンを作成するのが最善です。次は、Elastic Searchには有効です。

関連する問題