2013-05-24 3 views
1

내 몽고 DB를 샘플은이 샘플에서: 파이썬 pymongo에서 값 2를, MongoDB를

몽고

> db.pages.findOne() 

{ 
"_id" : ObjectId("519b6e81661b820d0e5d4f83"), 
"papers" : { 
    "text" : "RT @sydest: Sütaş reklamlarındaki inekleri erkekler seslendirdiği sürece bu cinsiyet ayrımcılığı bitmez...", 
    "ID" : null, 
    "paragraphs" : [ 
     { 
     "text" : "RT @sydest: Sütaş reklamlarındaki inekleri erkekler seslendirdiği sürece bu cinsiyet ayrımcılığı bitmez...", 
     "ID" : "0P107", 
     "sentences" : [ 
      { 
      "text" : "RT @sydest: Sütaş reklamlarındaki inekleri erkekler seslendirdiği sürece bu cinsiyet ayrımcılığı bitmez...", 
      "ID" : "0S107", 
      "words" : [ 
       { 
       "text" : "RT", 
       "ID" : "1W3" 
        }, 
        { 
        "text" : "sydest", 
        "ID" : "5W11" 
        }, 
        { 
        "text" : "Sütaş", 
        "ID" : "13W18" 
        }, 
        { 
        "text" : "reklamlarındaki", 
        "ID" : "19W34" 
        }, 
        { 
        "text" : "inekleri", 
        "ID" : "35W43" 
        }, 
        { 
        "text" : "erkekler", 
        "ID" : "44W52" 
        }, 
        { 
        "text" : "seslendirdiği", 
        "ID" : "53W66" 
        }, 
        { 
        "text" : "sürece", 
        "ID" : "67W73" 
        }, 
        { 
        "text" : "bu", 
        "ID" : "74W76" 
        }, 
        { 
        "text" : "cinsiyet", 
        "ID" : "77W85" 
        }, 
        { 
        "text" : "ayrımcılığı", 
        "ID" : "86W97" 
        }, 
        { 
        "text" : "bitmez", 
        "ID" : "98W104" 
        } 
       ] 
      } 
     ] 
    } 
] 
} 
} 

, 나는 하나의 종이있다. 종이에는 문단이 있고 값 문장 목록이 있습니다. 마찬가지로 나는 단어 키와 가치 단어 목록 setences 요소에 있습니다.

"ID"가 "W"인 모든 "텍스트"를 가져오고 싶습니다. 간단히 말해, 모든 문서에서 모든 단어를 한 번에 하나의 목록 또는 튜플로 가져 오려고합니다. 감사.

답변

2

나는 당신이 원하는 것을 성취 할 수있는보다 아름다운 방법이 있다고 확신하지만 여기는 find()을 사용했다.

MongoDB의 쿼리 :

db.so.find({'papers.paragraphs': {$elemMatch: {'sentences': {$elemMatch: {'words': {$elemMatch: {'ID': {$regex: 'W'}}}}}}}}, {'papers.paragraphs.sentences.words.text': 1}).pretty(); 

파이썬 코드 : 도움이

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import pymongo 

mongo_db = pymongo.MongoClient().test 

cursor = mongo_db.so.find({'papers.paragraphs': 
           {'$elemMatch': 
            {'sentences': 
             {'$elemMatch': 
               {'words': 
                {'$elemMatch': 
                 {'ID': {'$regex': 'W'}}}}}}}}, 
          {'papers.paragraphs.sentences.words.text': 1}) 

results = [] 
for result in cursor: 
    for paragraph in result['papers']['paragraphs']: 
     for sentence in paragraph['sentences']: 
      for word in sentence['words']: 
       results.append(word['text']) 

print results # prints [u'RT', u'sydest', ... ] 

희망.

+0

완벽하게 작동합니다. 고마워요! – Samed