2016-10-17 4 views
-1

私はmongodbに次のjson構造を持っています。'LIKE'ステートメントを使用してmongoengineのオブジェクトをフィルタリングする方法は?

{ 

    "country": "spain", 
    "language": "spanish", 
    "words": [ 
     { 
      "word": "hello1", 
      .... 
     }, 
     { 
      "word": "hello2", 
      .... 
     }, 
      { 
      "word": "test", 
      .... 
     }, 
     ] 
} 

特定の部分文字列が一致する「単語」リスト内のすべての辞書を取得しようとしています。マッチのために

次のクエリでのみ動作します「hello1」と「hello2」:私は部分文字列を持っている場合は

例えば、私は私の文書は言葉を持つ2つの辞書を与えるmongoengineを使用してクエリを実行すべきか、その後、「HEL」部分文字列ではない単語。配列から、基準に一致する最初の要素が返される(mongoengineでmatch$elemMatchを使用

data = Data.objects.filter(words__match={"word":"hel"}) 
    // data is empty in this case([]) 

答えて

1

あなたの配列から、一致するすべての要素を返すために集約を使用する必要があります。

pipeline = [ 
    { "$unwind": "$words" }, 
    { "$match": {"words.word": {"$regex": "hel"} } }, 
    { "$project": {"word":"$words.word", "_id":0} }, 
] 

Article.objects.aggregate(*pipeline) 

結果:

{u'word': u'hello1'} 
{u'word': u'hello2'} 

注意、あなたがそう事前にすべてのフィールドを知っている必要があり、このプロジェクトの段階を使用してプロジェクションでそれらを指定して戻すことができます。

あなたはまた、すべてのフィールドを返すために、異なる出力のために、このプロジェクトを使用しますが、言葉のdict "に包まれた可能

pipeline = [ 
    { "$unwind": "$words" }, 
    { "$match": {"words.word": {"$regex": "hel"} } }, 
    { "$project": {"words":1, "_id":0} }, 
] 

結果:

{u'words': {u'otherfield': 1.0, u'word': u'hello1'}} 
{u'words': {u'otherfield': 1.0, u'word': u'hello2'}} 
関連する問題