【发布时间】:2022-01-12 15:31:54
【问题描述】:
我的 MongoDB 数据库中有很多集合。 聚合工作很好,但我无法将某些字段推送到我需要的输出,
集合 A 是:
{
_id: some mongodbID
//...fields
items: [
{
_id: someId,
color: someId <---- Im aggregate this with lookup
neededFieldToPush: 123
},
{
_id: someId,
color: someId <---- Im aggregate this with lookup
neededFieldToPush: 566
}
]
}
我的查询是:
await Invoice.aggregate([
{ $match: query },
{ $unwind: "$items" },
//colors
{
$lookup: {
from: "colors",
localField: "items.itemColor",
foreignField: "_id",
as: "itemColor"
}
},
{
$addFields: {
"prMove.itemColor": { $arrayElemAt: ["$itemColor.colorName", 0] },
}
},
{
$group: {
_id: "$_id",
items: { $push: "$items" }, <-- original items
prMove: { $push: "$prMove" },
}
},
])
.sort({date: -1})
.skip(+req.query.offset)
.limit(+req.query.limit)
我需要这样的输出:
_id: someId,
items: [//original items],
prMove: [
{
itemColor: some color name, <--- it's works fine
neededFieldToPush: 123
},
{
itemColor: some color name, <--- it's works fine
neededFieldToPush: 566
},
]
那么,我如何将neededFieldToPush 字段推入prMove 对象?
谢谢
【问题讨论】:
标签: mongodb mongoose aggregation-framework