これはちょっと混乱します。 私は$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" ] ] }
問題がstate
とcity
フィールドをconcatingています。 ここにもう一度質問します。どのようにしてconcatすることができますdocument.state
、_
とdocument.city
? (それは、複数の要素を持っている場合)