2015-06-04 169 views
0

我在我的MongoDB以下JSON文檔,我加入mingoimport。蒙戈返回一個數組元素

我試圖從問題的數組,其中theQuestion等於「Q1」返回單個元素。

 { 
 
    "questions": [ 
 
    { 
 
     "questionEntry": { 
 
     "id": 1, 
 
     "info": { 
 
      "seasonNumber": 1, 
 
      "episodeNumber": 1, 
 
      "episodeName": "Days Gone Bye" 
 
     }, 
 
     "questionItem": { 
 
      "theQuestion": "q1", 
 
      "attachedElement": { 
 
      "type": 1, 
 
      "value": "" 
 
      } 
 
     }, 
 
     "options": [ 
 
      { 
 
      "type": 1, 
 
      "value": "o1" 
 
      }, 
 
      { 
 
      "type": 1, 
 
      "value": "o1" 
 
      } 
 
     ], 
 
     "answer": { 
 
      "questionId": 1, 
 
      "answer": 1 
 
     }, 
 
     "metaTags": [ 
 
      "Season 1", 
 
      "Episode 1", 
 
      "Rick Grimmes" 
 
     ] 
 
     } 
 
    }, 
 
    { 
 
     "questionEntry": { 
 
     "id": 1, 
 
     "info": { 
 
      "seasonNumber": 1, 
 
      "episodeNumber": 1, 
 
      "episodeName": "Days Gone Bye" 
 
     }, 
 
     "questionItem": { 
 
      "theQuestion": "q2", 
 
      "attachedElement": { 
 
      "type": 1, 
 
      "value": "" 
 
      } 
 
     }, 
 
     "options": [ 
 
      { 
 
      "type": 1, 
 
      "value": "o2" 
 
      }, 
 
      { 
 
      "type": 1, 
 
      "value": "o2" 
 
      } 
 
     ], 
 
     "answer": { 
 
      "questionId": 1, 
 
      "answer": 1 
 
     }, 
 
     "metaTags": [ 
 
      "Season 1", 
 
      "Episode 1", 
 
      "Rick Grimmes", 
 
      "Glenn Rhee" 
 
     ] 
 
     } 
 
    } 
 
    ] 
 
}

我跑的查詢db.questions.find({"questions.questionEntry.questionItem.theQuestion" : "q1"})但這retruned整個文件(包括questionEntry的問題陣列

我已經試過db.questions.find({"questions.questionEntry.questionItem.theQuestion" : "q1"}, _id:0," questions.questionItem": {$elemMatch : {theQuestion: "q1"}}})

但得到以下錯誤: Error: error: { "$err" : "Can't canonicalize query: BadValue Cannot use $elemMatch projection on a nested field.", "code" : 17287

有沒有一種方法,我可以限制其包含它的結果只是數組元素?

感謝

+0

使用限制()來限制你的序列號,並跳過()跳轉到具體項目 –

+0

你可以骨料使用和放鬆,僅匹配問題 – The6thSense

回答

3
db.questions.find({},{"questions.questionEntry.questionItem.theQuestion" : "q1"}); 

db.questions.find({"questions.questionEntry.questionItem.theQuestion" : "q1"},{'questions.$':1}); 

請嘗試這些。

+0

第一個查詢只會給外地'questions.questionEntry.questionItem.theQuestion'的所有問題。第二個查詢是OP想要的。 – thegreenogre

+0

@Yathish偉大的東西第二個就是我一直在尋找,但第一個選項也需要了解的。 – TripVoltage

1

如果你想使用$elemMatch查詢應該是:

db.questions.find(
    {"questions.questionEntry.questionItem.theQuestion" : "q1"}, 
    { 
     '_id':0, 
     "questions": { 
      $elemMatch : {"questionEntry.questionItem.theQuestion": "q1"} 
     } 
    } 
)