2016-07-06 24 views
4

我有什麼

我有以下證件進入我的匯聚管道:

[ 
    { 
     "email" : "[email protected]", 
     "name" : "Organization Name", 
     "users" : [ 
      { 
       "lastName" : "Nye", 
       "firstName" : "Bill", 
       "email"  : "[email protected]" 
      }, 
      { 
       "lastName" : "Rogers", 
       "firstName" : "Mr.", 
       "email"  : "[email protected]" 
      } 
     ] 
    }, 
    ... 
] 

我想要什麼

使用$project我想在每個陣列的$concatfirstNamelastName領域子文件得到以下結果:

{ 
    "email" : "[email protected]", 
    "name" : "Organization Name", 
    "users" : [ 
     { 
      "name" : "Bill Nye", 
      "email" : "[email protected]" 
     }, 
     { 
      "name" : "Mr. Rogers", 
      "email" : "[email protected]" 
     } 
    ] 
} 

我已經試過 - 嘗試#1

我已經試過在聚集:

db.organizations.aggregate([ 
    { 
     $project: { 
      email : 1, 
      name : 1, 
      users : { 
       name : { $concat : [ "$users.firstName", " ", "$users.lastName" ] }, 
       email : 1 
      } 
     } 
    } 
]); 

...但我得到以下錯誤:

$concat only supports strings, not Array

我」什麼已經試過 - 嘗試#2

我也試過以下聚合:

db.organizations.aggregate([ 
    { 
     $project: { 
      email : 1, 
      name : 1, 
      users : { 
       name : { $concat : [ "$firstName", " ", "$lastName" ] }, 
       email : 1 
      } 
     } 
    } 
]); 

...但是name總是返回null

我覺得這應該是一個相對簡單的事情,但是,我完全難住。

如何獲得我正在查找的結果?

回答

6

您可以簡單地通過$project爲此荷蘭國際集團您的文檔,並使用$map聚集變量操作者在$concat表達適用於每個項目在數組中,並返回與應用結果的數組。

db.organizations.aggregate(
    [ 
     { "$project": { 
      "email": 1, 
      "name": 1, 
      "users": { 
       "$map": { 
        "input": "$users", 
        "as": "u", 
         "in": { 
          "name": { "$concat" : [ "$$u.firstName", " ", "$$u.lastName" ] }, 
          "email": "$$u.email" 
         } 
       } 
      } 
     }} 
    ] 
) 
+0

雖然這個答案和@ chridam的答案一樣好,並且從另一個角度解決問題,但我最終使用了他的解決方案。謝謝你的時間! – docksteaderluke

+0

@docksteaderluke我知道你會使用這個解決方案;),因爲儘管事實上其他答案是「事實上正確的」,但它絕對不是要走的路。 – styvane

+0

謹慎闡述?爲什麼不走這條路? – docksteaderluke

相關問題