我使用Mongo 4.4。 我正在尝试创建一个 mongo 聚合,它会返回一个包含嵌套数组的文档。指定上下文: 我有报价,其中包含模块,其中包含项目,其本身包含注释。我有每个实体的集合:
offers: {
_id: '64a6c6ed3f24ff001b74cf9d',
name: 'offer name',
}
modules: {
_id: '64a6c6ed3f24ff001b74cfab',
name: 'module name',
offerId: '64a6c6ed3f24ff001b74cf9d',
}
items: {
_id: '5e984aea5e6df000399e6b97',
name: 'module name',
moduleId: '64a6c6ed3f24ff001b74cfab',
}
notes: {
_id: '64c78caf0e5791001b15833c',
name: 'note name',
itemId: '5e984aea5e6df000399e6b97',
}
通过我的查询,我想通过 _id 检索报价,并且此查询返回报价及其模块、每个模块的项目以及每个项目的注释。基本上是这样的对象:
offer: {
_id: "64a6c6ed3f24ff001b74cf9d",
name: "offer name",
modules: [
{
_id: "64a6c6ed3f24ff001b74cfab",
name: "module name",
items: [
{
_id: "5e984aea5e6df000399e6b97",
name: "item name",
notes: [
{
_id: "64c78caf0e5791001b15833c",
name: "note name"
},
{
// other note
},
...
]
},
{
// other item
},
...
]
},
{
// other module
},
...
]
}
我写了这个查询:
db.getCollection("offers").aggregate([
{
$match: {
_id: ObjectId('64a6c6ed3f24ff001b74cf9d'),
}
},
{
$lookup: {
from: 'modules',
localField: '_id',
foreignField: 'offerId',
as: 'modules',
},
},
{
$unwind: '$modules',
},
{
$lookup: {
from: 'items',
localField: 'modules._id',
foreignField: 'moduleId',
as: 'items',
},
},
{
$unwind: '$garantyItems',
},
{
$lookup: {
from: 'notes',
localField: 'garantyItems._id',
foreignField: 'itemId',
as: 'notes',
},
},
{
$group: {
_id: "$_id",
name: { $first: "$name" },
modules: {
$push: {
_id: "$modules._id",
name: "$modules.name",
items: {
$push: {
_id: "$garantyItems._id",
name: "$garantyItems.name",
notes: {
$push: {
_id: "$notes._id",
name: "$notes.name",
}
},
}
},
}
}
}
},
{
$project: {
_id: 1,
name: 1,
modules: 1,
}
},
]);
但是当我运行它时,我收到此错误:
Unrecognized expression '$push'
嵌套 $push 是不可能的吗?这种情况下如何才能达到想要的效果呢?
提前致谢。
$push
聚合运算符在嵌套值中无效。为了获得您想要的结果,请为每个级别使用单独的 $group,例如:
{$group:{
_id:{
_id:"$_id",
module:{_id:"$modules._id", name:"$modules.name"},
item:{_id:"$garantyItems._id", name:"$garantyItems.name"}
},
notes:{$push:{ _id:"$notes._id", name:"$notes.name"}}
}},
{$group:{
_id:{
_id:"$_id._id",
module:"$_id.module",
},
items:{$push:{_id:"$_id.item._id",name:"$_id:item.name",notes:"$notes"}}
}},
{$group:{
_id:"$_id._id",
modules:{$push:{_id:"$_id.module._id",name:"$_id.module.name",items:"$items"}}
}}