【发布时间】:2017-06-11 21:52:17
【问题描述】:
这有点令人困惑。
我正在尝试 $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 字段。
所以这里再次提出问题。如何连接 document.state、_ 和 document.city?
【问题讨论】:
标签: node.js mongodb mongodb-query aggregation-framework