【发布时间】:2018-01-12 12:41:40
【问题描述】:
在一个简化的数据模型中,我有三种类型的文档:项目、用户和分配。用户和项目存储在他们自己的集合中,而分配嵌入在项目中。示例项目可能如下所示:
{
"_id" : ObjectId("xxx"),
"name" : "yyy",
"assignments" : [
{
"assignmentDate" : ISODate("2018-01-11T10:05:20.125Z"),
"user" : ObjectId("zzz"),
},
{
"assignmentDate" : ISODate("2018-01-12T10:05:20.125Z"),
"user" : ObjectId("iii"),
}
]
}
我想查询当前分配给给定用户的所有项目。这个聚合管道完成了这项工作:
db.Item.aggregate([
{
$addFields: {
currentAssignment: { $arrayElemAt: ['$assignments', -1] }
}
},
{
$lookup: {
from: 'User',
localField: 'currentAssignment.user',
foreignField: '_id',
as: 'currentUser'
}
},
{
$match: {
'currentUser.name': { $eq: 'admin' }
}
}
]);
如何使用 Doctrine ODM Aggregation Builder 构建它? Stage::lookup 方法只接受 from 参数。如果我在聚合管道的计算字段上使用它(在本例中为currentAssignment),则会导致:
arguments to $lookup must be strings, localField: null is type null
也欢迎其他用于检索所述数据集的解决方案(如果可能,即使没有聚合?)。
【问题讨论】:
标签: mongodb aggregation-framework doctrine-odm