2016-04-25 27 views
2

我有一個集合「學生」。如何在對象中獲取一些字段?

{ 
    student:"Jone Doe", 
    class:"A", 
    subjects: 
    [ 
     {subject:"Math",teacher:"Linda","score":"82"}, 
     {subject:"English",teacher:"Jone","score":"52"}, 
     {subject:"History",teacher:"Maria","score":"32"}, 
    ] 
} 
{ 
    student:"Baby Doe", 
    class:"B", 
    subjects: 
    [ 
     {subject:"Math",teacher:"Hilary","score":"52"}, 
     {subject:"English",teacher:"Notham","score":"52"}, 
     {subject:"History",teacher:"Hamet","score":"32"}, 
    ] 
} 

我想獲得學生的學科「數學」的所有分數。

即時通訊使用aggregation得到

db.collection('studens').aggregate([ 
     {$match: {"subjects.subject" : "Math" } }, 
     {$project: { 
     _id:0, 
     subjects: { 
      $filter: { 
       input: "$subjects", 
       as: "subject", 
       cond: { $lte: [ "$$subject.subject", "Math" ] } 
      } 
     } 
     } 
    } 
]); 

而結果:

{subject:"Math",teacher:"Linda","score":"82"} 
{subject:"Math",teacher:"Hilary","score":"52"} 

但它顯示的所有字段,我要的結果(只顯示主題和得分):

{subject:"Math","score":"82"} 
{subject:"Math","score":"52"} 

如何做到這一點? 請幫幫我。

+0

好吧,但是我只是測試你的聚集..我得到:' 「結果」:[{ 「科目」: //所有值 ] },{ 「科目」: //所有值甚至英文和其他主題 ] } ]'這是你所得到的? – rahpuser

+0

將條件更改爲$ eq,現在我只得到數學主題文檔..這是您正在尋找的輸出嗎?不支持排除值,所以..你可以嘗試使用包含字段 – rahpuser

回答

1

我不知道應該如何做,因爲排除不支持,我會使用另一個投影包含所需的字段。 (這可能是一個更好的方法)。

讓我們試試這個:

db.collection('studens').aggregate([ 
     {$match: {"subjects.subject" : "Math" } }, 
     {$project: { 
      _id:0, 
      subjects: { 
       $filter: { 
        input: '$subjects', 
        as: 'subjects', 
        cond: {$eq: ['$$subjects.subject', 'Math']} 
       } 
      } 
     } 
    },{$project: {subjects: { subject:1, score:1}}} 
]); 

結果:

"result" : [ 
    { 
     "subjects" : [ 
      { 
       "subject" : "Math", 
       "score" : "82" 
      } 
     ] 
    }, 
    { 
     "subjects" : [ 
      { 
       "subject" : "Math", 
       "score" : "52" 
      } 
     ] 
    } 
] 

這是你在找什麼?

+0

的其他投影,謝謝你的支持,它的工作。而更好的方式呢? –

+0

我想不出這一秒。如果我有更好的主意,我會編輯答案。我很高興它幫助你。 – rahpuser

相關問題