首页 > 解决方案 > 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",                    
            }
},
...

标签: mongodbaggregation-framework

解决方案


您可以使用$unwind管道阶段来做到这一点

db.items.aggregate([
{
    $lookup: {
            from: "trends",
            localField: "itemid",
            foreignField: "itemid",
            as: "trend"
            }
    },
    $unwind:"$trend"
])

推荐阅读