Doctrine ODM:使用聚合构建器在聚合字段上创建$ lookup

时间:2018-01-12 12:41:41

标签: mongodb aggregation-framework doctrine-odm

在简化的数据模型中,我有三种类型的文档:项目,用户和分配。用户和项目存储在自己的集合中,而分配则嵌入在项目中。示例项可能如下所示:

{
    "_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

我们也欢迎使用其他解决方案(如果可能,甚至没有聚合?)来检索所描述的数据集。

1 个答案:

答案 0 :(得分:1)

Lookup阶段有更多方法,其中一个是localField,它在聚合阶段设置localField

相关问题