mongodb - Mongodb 聚合意外数组结果 - 需要从 $lookup 返回对象而不是数组
问题描述
我加入了两个集合,但是趋势的结果是一个数组,每个项目总是只有一个趋势,我如何去除数组内的趋势?
'项目'集合:
{
"itemid" : "370",
"name" : "A"
},
{
"itemid" : "378",
"name" : "B"
}
“趋势”系列
{
"itemid" : "370",
"max" : "715705",
},
{
"itemid" : "378",
"max" : "35346",
}
执行的命令:
db.items.aggregate([
{
$lookup: {
from: "trends",
localField: "itemid",
foreignField: "itemid",
as: "trend"
}
}
])
结果:
{
"itemid" : "370",
"name" : "A",
"trend" : [ // unexpected array, the result is always a single 'trend'
{
"itemid" : "370",
"max" : "715705",
}
]
},
...
预期的:
{
"itemid" : "370",
"name" : "A",
"trend" : { // yeah, without array
"itemid" : "370",
"max" : "715705",
}
},
...
解决方案
您可以使用$unwind管道阶段来做到这一点
db.items.aggregate([
{
$lookup: {
from: "trends",
localField: "itemid",
foreignField: "itemid",
as: "trend"
}
},
$unwind:"$trend"
])
推荐阅读
- php - .htaccess 更改后 Yii2 找不到 /backend/web
- azure-data-lake - ADX 中用于 ADLS 数据的外部表:无记录
- twitter-bootstrap - Vue Bootstrap 4 导航栏高度和下拉菜单在 Safari 上不起作用
- io - Sublime text 3 MinGW 构建
- html - Outlook 上的 HTML 表格未完全显示
- powershell - 如何将带引号的字符串作为参数传递给PowerShell中的可执行文件?
- django - Django添加新记录错误重复键值违反唯一约束“”Django Id不与数据库同步
- c# - 如何将 Json 文件添加到 Xamarin 表单?
- django - 如何将通过表单获取的字段与在 django 中创建的模型进行比较?
- regex - 正则表达式:匹配一个组但返回不同的字符串