【问题标题】:Finding parent documents based on a child ID根据子 ID 查找父文档
【发布时间】:2017-06-08 04:08:29
【问题描述】:

假设我有以下架构

let TutorialQuizSchema = new mongoose.Schema({
    groups: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Group' }]
});

let GroupSchema = new mongoose.Schema({
    members: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
    responses: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Response' }]
});

let UserSchema = new mongoose.Schema({
    name: {
        first: String,
        last: String
    }
});

给定一个用户 ID,是否可以查询所有将该用户作为其成员之一的组的所有教程测验?

我是聚合新手,但我认为应该是这样的

TutorialQuiz.aggreggate([
    {
        $unwind: '$groups'
    },
    { 
        $lookup: {
            from: 'groups',
            localField: 'groups',
            foreignField: '_id',
            as: 'group'
        }
    },
    {
        $unwind: '$group'
    },
    {
        $match: { 
            'group.members': { $in: [req.user._id] } 
        }
    }
]).exec((err, data) => {
    // etc
})

如果我是正确的,我唯一的问题是数据被展平了。是否可以将其展开以保持层次结构(就像我们只是在做一个find + populate 查询)?

注意:如果有更好/更简单的方法可以做到这一点,我也愿意接受建议。

【问题讨论】:

  • 你的 mongo 服务器版本是多少?
  • @Veeram 应该是最新的。如果没有,我可以随时更新。

标签: mongodb mongoose left-join grouping


【解决方案1】:

您可以在不使用$unwinding 的情况下直接$lookup objectIds 并使用$filter 而不是$addFields 阶段内的第二个$unwind 来过滤user_id 值存在于members 数组中的组3.4版本。

有点像

TutorialQuiz.aggreggate([
    { 
        $lookup: {
            from: 'groups',
            localField: 'groups',
            foreignField: '_id',
            as: 'group'
        }
    },
    {
      $addFields: {
         group: {
            $filter: {
               input: "$group",
               as: "group",
               cond: { $in: [ req.user._id, "$$group.members" ] }
            }
         }
      }
   }
])

【讨论】:

    猜你喜欢
    • 2016-12-25
    • 2016-03-12
    • 2022-09-27
    • 1970-01-01
    • 2020-04-21
    • 2021-01-13
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    相关资源
    最近更新 更多