gpt4 book ai didi

Mongodb 聚合意外的数组结果 - 需要从 $lookup 返回一个对象而不是数组

转载 作者:行者123 更新时间:2023-12-02 19:43:39 25 4
gpt4 key购买 nike

我正在连接两个集合,但趋势的结果是一个数组,每个项目始终只有一个趋势,如何删除数组内的趋势?

“项目”集合:

{
"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"
])

关于Mongodb 聚合意外的数组结果 - 需要从 $lookup 返回一个对象而不是数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59723396/

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