【问题标题】:Get all fields in one collection and specific field in other collection with $lookup aggregation使用 $lookup 聚合获取一个集合中的所有字段和另一个集合中的特定字段
【发布时间】:2018-03-22 05:10:18
【问题描述】:

我有 10 个字段的集合 timestamps。 并收集ie_settings 5 个字段。

我使用$lookup 加入他们,但它会返回所有字段。

我也尝试将$project 用于返回特定字段。

我想要的是显示来自timestamps 的所有字段 以及来自ie_settings的特定字段

这是我的尝试:

Timestamp.aggregate([
                { $match: {
                        $or: [
                            { current_status: '60min break now' },
                            { current_status: 'Time out' }
                        ],
                        createdAt: { $gte: date_from, $lt: date_to } }
                },
                { $lookup: {
                        from: "individual_employment_settings",
                        localField: "staff_id",
                        foreignField: "staff_id",
                        as: "ie_settings" }
                },
                {
                    $project: {
                        "ie_settings.branch_office": 1
                    }
                }
            ])

但它只会输出branch_office。我不想在$project 中列出所有timestamp fields。 谢谢。

【问题讨论】:

  • 在 3.4 中使用 { $addFields: { "ie_settings.branch_office": 1}}

标签: mongodb aggregation-framework


【解决方案1】:
Timestamp.aggregate([
                { $match: {
                        $or: [
                            { current_status: '60min break now' },
                            { current_status: 'Time out' }
                        ],
                        createdAt: { $gte: date_from, $lt: date_to } }
                },
                { $lookup: {
                        from: "individual_employment_settings",
                        localField: "staff_id",
                        foreignField: "staff_id",
                        as: "ie_settings" }
                },
                {
                    $project: {
                         document: "$$ROOT",
                        "ie_settings.branch_office": 1
                    }
                }
            ])

【讨论】:

  • 我试过了,但它也显示了两个集合的所有字段。
猜你喜欢
  • 2017-03-14
  • 2017-07-12
  • 2021-08-15
  • 1970-01-01
  • 2017-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-01
  • 1970-01-01
相关资源
最近更新 更多