2016-12-05 1 views
2

こんにちは。それはそれはstring1財産だとstring2プロパティは、内容が含まれていますので、私は唯一のDATA1を返すようにしたいクエリの後MongoDBでは、ある文字列フィールドに別の文字フィールドが含まれている場合にクエリを実行する方法

data1= { 
    "string1":"abc", 
    "string2":"abcde" 
} 

data2= { 
    "string1":"abc", 
    "string2":"ftgr" 
} 

: はMongoDBので、私はこのようなコレクションを持っています。どうすればこの作品を作れますか?どこで$を使うべきか正規表現を使うべきですか?誰かが先端を指すことができるなら、非常に非常に感謝します。

+0

これを行うクエリが必要な場合、またはクエリの終了後に結果をフィルタリングする場合は、私には少し不明です。 –

+0

また、ここでは、$ whereまたはaggregationのどちらかを使用して回答しているようです。https://www.codeschool.com/discuss/t/how-to-query-based-on-the-variable-value-stored -in-another-field/20979/3 –

答えて

2

あなたはstring1ためRegExpを作成し、string2に対してそれをテストすることによって$whereでこれを行うことができます。

db.test.find({$where: 'RegExp(this.string1).test(this.string2)'}) 

をしかし、あなたは$indexOfCPを使用して、より効率的にこれを行うことができ3.4+にMongoDBを使用している場合集計演算子:また$redactを使用して

db.test.aggregate([ 
    // Project the index of where string1 appears in string2, along with the original doc. 
    {$project: {foundIndex: {$indexOfCP: ['$string2', '$string1']}, doc: '$$ROOT'}}, 
    // Filter out the docs where the string wasn't found 
    {$match: {foundIndex: {$ne: -1}}}, 
    // Promote the original doc back to the root 
    {$replaceRoot: {newRoot: '$doc'}} 
]) 

以上の直接的:

db.test.aggregate([ 
    {$redact: { 
     $cond: { 
      if: { $eq: [{$indexOfCP: ['$string2', '$string1']}, -1]}, 
      then: '$$PRUNE', 
      else: '$$KEEP' 
     } 
    }} 
]) 
関連する問題