这有点令人困惑.我正在尝试$group
结果,aggregatation
而grouping
我们创造了新的领域,其中包括两个不同领域的结合.嗯.实际上我不愿意分享数据库的结构并让你感到困惑.但描述并不是解释性的.
所以我们走了.
学生集合
{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
田地相结合.所以这里的问题又来了.我怎样才能Concat的document.state
,_
和document.city
?
$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"] } } } ])