【问题标题】:Mongodb aggregation lookup out put and again perform lookup on the outputMongodb聚合查找输出并再次对输出执行查找
【发布时间】:2021-11-14 17:00:22
【问题描述】:

查询如下图

db.assignmentdetails.aggregate([
{ "$match": { _id: ObjectId("614887ee0e02d153ecc6dbc3") } },
  { "$addFields": {
        "convertedClassId": { $toObjectId: "$className" },
   
      }
    }},
       {
      "$lookup": {
        "from": "combinedgradesectiondetails",
        "localField": "convertedClassId",
        "foreignField": "_id",
        "as": "classDetails"
      }
    },
      
])

输出:

{
            "_id" : ObjectId("614872917500193be80ca896"),
            "gradeId" : "6148728f7500193be80ca86d",
            "sectionId" : "614872917500193be80ca892",
            "maximumStudents" : 35,
            "maximumCourse" : 5,
            "updated" : ISODate("2021-09-20T11:37:53.499Z"),
            "__v" : 0
        }

再次在此输出上,我必须从另一个集合(等级详细信息)中查找来自另一个集合(部分详细信息)的 sectionId,但这仅在现有查询的此输出上执行,不确定是否有办法在 mongoDB 聚合中,请指向文档或示例查询以实现此目的

【问题讨论】:

    标签: mongodb collections match lookup aggregation


    【解决方案1】:

    您可以一个接一个地链接 $lookup。

    如果需要,使用 $unwind 来展平数组。

    您可以选择在每次 $lookup 之后使用 $project stage,以便为进一步的阶段提供仅必填字段。

    这是一个参考示例:

    [{
        $match: {
            status: "ACTIVE"
        }
    }, {
        $lookup: {
            from: 'place',
            localField: 'place_id',
            foreignField: 'place_id',
            as: 'place'
        }
    }, {
        $unwind: {
            path: '$place'
        }
    }, {
        $project: {
            custom_hour_id: 1,
            place_id: 1,
            menu_id: 1,
            object_type: 1,
            description: 1,
            day: 1,
            option: 1,
            closed_all_day: 1,
            status: 1,
            audit: 1,
            place: {
                place_id: 1,
                name: 1,
                city: 1
            }
        }
    }, {
        $lookup: {
            from: 'user_DEV1',
            localField: 'audit.created_by',
            foreignField: 'user_id',
            as: 'created_by_user'
        }
    }, {
        $unwind: {
            path: '$created_by_user'
        }
    }, {
        $project: {
            custom_hour_id: 1,
            place_id: 1,
            menu_id: 1,
            object_type: 1,
            description: 1,
            day: 1,
            option: 1,
            closed_all_day: 1,
            status: 1,
            audit: 1,
            place: 1,
            created_by_user: {
                user_id: 1,
                email: 1,
                display_name: 1
            }
        }
    }]
    

    【讨论】:

    • true 但第一次查找的输出我想在第二次使用
    • 第一阶段输出是第二阶段输入,一直持续到最后阶段。
    猜你喜欢
    • 2018-03-14
    • 2018-10-14
    • 2018-12-28
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 2019-11-18
    • 2017-11-08
    相关资源
    最近更新 更多