mongoDB聚合$lookup并从现有数组中推送一些信息



我的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
  • $addFieldsitems中的颜色名称编辑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"
}
}
])

游乐场

最新更新