我的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
对象中呢?
谢谢
查询的实现成本很高,因为您使用了$unwind
阶段和$group
阶段,这将影响性能,
第二件事是$sort
、$skip
和$limit
函数不会对猫鼬的聚合函数起作用,你可以使用阶段,
第三件事是在$match
阶段之后立即使用sort、$skip
和$limit
阶段,因此在对所需字段创建索引时,它将提高性能。
改进的查询,
$match
您的查询$sort
分拣台$skip
级通过偏移$limit
阶段限制文档$lookup
,颜色采集并通过items.color
作为localField
$addFields
用items
中的颜色名称编辑items
阵列$map
迭代items
数组的循环$reduce
迭代查找得到的itemColor
数组结果的循环,检查条件_id
是否匹配,然后在color
字段中获取颜色名称和设置值$mergeObjects
合并项目对象的新color
字段和当前字段$$REMOVE
删除itemColor
阵列,因为现在不需要它
let offset = req.query.offset;
let limit = req.query.limit;
await Invoice.aggregate([
{ $match: query },
{ $sort: { date: -1 } },
{ $skip: offset },
{ $limit: limit },
{
$lookup: {
from: "colors",
localField: "items.color",
foreignField: "_id",
as: "itemColor"
}
},
{
$addFields: {
items: {
$map: {
input: "$items",
as: "i",
in: {
$mergeObjects: [
"$$i",
{
color: {
$reduce: {
input: "$itemColor",
initialValue: "",
in: {
$cond: [
{ $eq: ["$$this._id", "$$i._id"] },
"$$this.colorName",
"$$value"
]
}
}
}
}
]
}
}
},
itemColor: "$$REMOVE"
}
}
])
游乐场