2017-01-26 10 views
3

これはちょっと混乱します。 私は$groupの結果をaggregatationとしていますが、groupingの間に2つの異なるフィールドの連結で構成される新しいフィールドを作成しています。うーん。実際に私はデータベースの構造を共有し、あなたを混乱させたくありませんでした。しかし説明は説明的ではありません。

だからここに行きます。私が取得したい何

学生のコレクション

{id: "1", school: "georgia tech"} 

大学のコレクション

{name: "georgia tech" , state: "Georgia" , city: "Atlanta"} 

?私が手に入れたい

{id: 1, name: "georgia tech" , place: "Georgia_Atlanta"} 

私はこれを達成するために何をしましたか?

db.student.aggregate([ 
    {$match: {"id": "1"}}, 
    {$lookup: {from: "university" , localField: "school" , foreignField: "name", as: "document"}}, 
    {$group: {_id: "$id", name: {$push: "$school"}, place: {$push: {$concat: ["$document.state" , "_" , "$document.city"]}}}} 
]) 

ただし、次のようにエラーが発生します。

assert: command failed: { 
    "ok" : 0, 
    "errmsg" : "$concat only supports strings, not Array", 
    "code" : 16702 
} 

一方、

db.student.aggregate([ 
    {$match: {"id": "1"}}, 
    {$lookup: {from: "university" , localField: "school" , foreignField: "name", as: "document"}}, 
    {$group: {_id: "$id", name: {$push: "$school"}, place: {$push: "$document.state" }}}  
]) 

として返されます。

{ "_id" : "1", "name" : [ "georgia tech" ], "place" : [ [ "Georgia" ] ] } 

問題がstatecityフィールドをconcatingています。 ここにもう一度質問します。どのようにしてconcatすることができますdocument.state_document.city? (それは、複数の要素を持っている場合)

答えて

5

$lookupを使用する(それは単一の要素を持つ場合)、それを平らにする$arrayElemAt演算子を使用する必要があるので、配列を返すまたは$unwind。だから、最後に、あなたが希望する結果を得るために、次のパイプラインを実行することができます:

db.student.aggregate([ 
    { "$match": { "id": "1" } }, 
    { 
     "$lookup": { 
      "from": "university", 
      "localField": "school", 
      "foreignField": "name", 
      "as": "document" 
     } 
    }, 
    { 
     "$project": { 
      "id": 1, 
      "university": { "$arrayElemAt": [ "$document", 0 ] } 
     } 
    }, 
    { 
     "$project": { 
      "id": 1, 
      "name": "$university.name", 
      "place": { "$concat": ["$university.state", "_", "$university.city"] } 
     } 
    }  
]) 
1

を私は正確なユースケースを知らないが、あなたはGROUPBYを使用する必要がある場合、これは作業バージョンです。それ以外の場合、chridamは簡単なアプローチを使用しています:

db.student.aggregate([ 
    {$match: {"id": "1"}}, 
    {$lookup: {from: "university" , localField: "school" , foreignField: "name", as: "document"}}, 
    {$group: {_id: "$id", name: {$first: "$school"}, tempplace: {$first: "$document" }}}, 
    {$unwind: "$tempplace"}, 
    {$project: {id: 1, name: 1, place: {$concat: ["$tempplace.state", "_", "$tempplace.city"]}}} 
]) 
関連する問題