【问题标题】:Doctrine ODM: create $lookup on aggregated field with aggregation builderDoctrine ODM:使用聚合构建器在聚合字段上创建 $lookup
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2017-10-16
      • 2019-11-08
      • 2016-07-16
      • 2019-01-27
      • 2019-04-18
      • 2016-10-14
      • 1970-01-01
      • 2022-10-12
      • 2022-01-05
      相关资源
      最近更新 更多