gpt4 book ai didi

node.js - $concat 聚合 mongodb

转载 作者:可可西里 更新时间:2023-11-01 09:24:06 26 4
gpt4 key购买 nike

这有点令人困惑。我正在尝试 $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" ] ] }

问题是连接 statecity 字段。所以这里的问题又来了。如何连接 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"] }
}
}
])

关于node.js - $concat 聚合 mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41873241/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com