2016-01-23 80 views
0

下面的文檔有學生的dob和它的父母的dob。MongoDB投影到數組

{ 
    "_id" : ObjectId("56a31573a3b1f89cb895abd3"), 
    "dob" : { 
     "isodate" : ISODate("1996-01-21T18:30:00.000+0000") 
    }, 
    "parent" : [ 
     { 
      "dob" : { 
       "isodate" : ISODate("1956-07-21T18:30:00.000+0000") 
      }, 
      "type" : "father" 
     }, 
     { 
      "dob" : { 
       "isodate" : ISODate("1958-11-01T18:30:00.000+0000") 
      }, 
      "type" : "mother" 
     } 
    ] 
} 

在應用程序的用例中的一個,最好是接收在下面的格式

{ 
    "_id" : ObjectId("56a31573a3b1f89cb895abd3"), 
    "dob" : { 
     "isodate" : ISODate("1996-01-21T18:30:00.000+0000") 
    }, 
    "type" : "student" 
}, 
{ 
    "_id" : ObjectId("56a31573a3b1f89cb895abd3"), 
    "dob" : { 
     "isodate" : ISODate("1956-07-21T18:30:00.000+0000") 
    }, 
    "type" : "father" 
}, 
{ 
    "_id" : ObjectId("56a31573a3b1f89cb895abd3"), 
    "dob" : { 
     "isodate" : ISODate("1958-11-01T18:30:00.000+0000") 
    }, 
    "type" : "mother" 
} 

的方法是$project字段成數組,然後$unwind該陣列輸出。但是,投影不允許我創建數組。

我相信$group及其關聯的聚合不能用作我的操作是在管道中的同一文件。

這可能嗎? 注 - 我也可以靈活地更改文檔設計。

+0

@布雷克個什麼想法 –

+0

u能解釋更詳細? – null1941

+0

我已經添加了3.2的解決方案,任何類似的3.0? –

回答

0

對於蒙戈3.0

在這裏,我已經包括一個[null]陣列,它給了我使用$ setDiffernce和$ COND的組合來插入投影陣列的選項。這個的輸出被賦予$ setUnion和$parent數組。

db.p1.aggregate(
{ "$project": { 
     "allVal": { 
      '$setUnion': [ 
      {"$setDifference": [ 
       { "$map": { 
        "input": [null], 
        "as": "type", 
        "in": { "$cond": [ 
         {"$eq": ["$$type", null]}, 
         {dob:"$dob", type:{$literal:'student'}}, 
         null       
        ]} 
       }}, 
       [null] 
      ]} 

      , 
      '$parent' 
      ] 
     } 
    }}, 
    {$unwind : '$allVal'} 

) 

對於蒙戈3.2

感覺,因爲我已經避免$ setDifference和$文字黑客調整天堂。

db.p1.aggregate([ 
{ 
    $project:{ 
     parent : 1, 
     type: {$literal : 'student'}, 
     'dob.isodate' : 1 
    } 
}, 
{ 
    $project:{ 
     allValues: { $setUnion: [ [{dob:"$dob", type:'$type'}], "$parent" ] } 
    } 
}, 
{ 
    $unwind : '$allValues' 
} 
]) 

在第一突起,我增加了稱爲類型

在第二投影新的領域,我創建與同一文檔的2個不同的節點的新數組。

目前該解決方案適用於蒙戈3.2

+0

爲什麼你認爲第二個選項只適用於3.2版本?在2.6版本中增加了'$ literal'這裏是[發佈說明](https://docs.mongodb.org/manual/release-notes/2.6/#release-notes-for-mongodb-2-6)。在版本3.0以後還有更好的方法來完成這項工作,3.2 – styvane

+0

$ project作爲數組被添加到3.2 –

+0

這不是事實。 – styvane