2016-10-17 3 views
-1

나는 내 mongodb에서 다음 json 구조를 가지고있다.'LIKE'문을 사용하여 mongoengine의 객체를 필터링하는 방법은 무엇입니까?

{ 

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

나는 모든 사전을 특정 부분 문자열이 일치하는 '단어'목록 안에 넣으려고합니다. 일치를위한

다음 쿼리에만 작동 'hello1'와 'hello2': 나는 문자열이있는 경우

예를 들어, 내 문서의 단어로 두 개의 사전을 제공 mongoengine를 사용하여 쿼리하는 방법 다음, '그러는' 단어는 부분 문자열이 아닙니다. 어레이에서의 조건과 일치하는 첫 번째 요소를 반환 (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'} 

주, 당신은 사전에 모든 필드를 알아야이 프로젝트 단계를 사용하여 이렇게 투영에서 그들을 지정할 수 있습니다.

당신은 또한 '단어 딕셔너리'의 모든 필드를 반환하지만 포장하기 위해, 다른 출력이 프로젝트를 사용할 수 있습니다

:

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'}} 
관련 문제