2017-08-03 83 views
2

我想從Mongo數組中返回特定的字段,並且遇到問題。Mongo:返回數組切片中的特定字段

讓我們說,我們有一個像這樣的文件:

{ 
    "student":"Bob", 
    "report_cards": [ 
    { 
     "Year":2016, 
     "English":"B", 
     "Math":"A" 
    }, 
    { 
     "Year":2015, 
     "English":"B", 
     "Math":"A" 
    } 
    ] 
} 

我想返回如下:

{"Student": "Bob", {"English":"B"}} 

基本上,我只需要在第一個元素的成績單陣中,並只返回英文字段。

我知道這是周圍的東西:

db.collection.find({},{"Student":1, "report_cards":{$slice:1}}); 

但是這一點,當然,結果全陣列(年,英語,數學)返回英寸我試過以下內容:

db.collection.find({},{"Student":1, "report_cards.$.english":{$slice:1}}) 
db.collection.find({},{"Student":1, "report_cards":{$slice:1, "$.english"}}); 

但這些不正確。

如何從數組結果中的obj中簡單地返回一個字段?

謝謝!

回答

2

您可以使用聚合框架來獲取值

db.test.aggregate 
([{$project:{_id:0, 
student:'$student', 
English:{ $arrayElemAt: ['$report_cards.English',0] 
}}}]) 
1

AFAIK沒有內置運營商在嵌入式文件過濾鍵值對。

您可以使用運算符組合來實現最新的3.4版本。

以下查詢使用$arrayElemAt獲得第一元件在report_cards隨後$objectToArray轉換爲陣列視圖(的kv雙陣列)和$filterEnglish鍵,以保持匹配的密鑰值對和$arrayToObject轉換回文件。

喜歡的東西

{ 
    "$project": { 
    "output": { 
     "$arrayToObject": { 
     "input": { 
      "$filter": { 
      "input": { 
       "$objectToArray": { 
       "$arrayElemAt": [ 
        "$report_cards", 
        0 
       ] 
       } 
      }, 
      "as": "result", 
      "cond": { 
       "$eq": [ 
       "$$result.k", 
       "English" 
       ] 
      } 
      } 
     } 
     } 
    } 
    } 
} 
相關問題