【问题标题】:Can I use projection on $lookup? [duplicate]我可以在 $lookup 上使用投影吗? [复制]
【发布时间】:2020-04-30 06:12:11
【问题描述】:

我有这个功能:

return db.collection( process.env.SPACECOLLECTION ).aggregate( [
            {
                $lookup: {
                    from: "users",
                    localField: "challengers",
                    foreignField: "_id",
                    as: "members"
                }
            }
        ] ).toArray();

我得到了什么:

{
      _id: 5dfa26f46719311869ac1756,
      tokens: [],
      friends: [Array],
      incomingFriendRequest: [],
      incomingSpaceInvites: [],
      name: 'Account 2',
      email: 'account2@gmail.com',
      password: '$2b$10$VRrdAdFdGAlqN5lZ/J/za.S5gqjCpII8LBhPLNiTmHrFDHvESRRTC',
      spaces: [Array]
    }

我想要什么:

{
      _id: 5dfa26f46719311869ac1756,
      name: 'Account 2',
      email: 'account2@gmail.com',
    }

我的问题是“用户”集合包含密码和令牌等字段。这是我在执行此查找功能时不想收到的东西。

基本上我的问题是:有什么方法可以从我得到的文档中选择哪些字段,类似于投影的工作方式,例如 findOne?

如果不是,我将如何处理?从数据库中获取后删除后端的字段?

谢谢!

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    是的,你可以像这样使用$lookup with a custom pipeline

    return db.collection( process.env.SPACECOLLECTION ).aggregate( [
        {
            $lookup: {
                from: "users",
                let: { challengers : "$challengers"},
                pipeline: [
                    { $match:
                            { $expr: // i'm assuming challengers is an array.
                                    { $in: [ "$_id",  "$$challengers" ] },
                            }
                    },
                    { $project: { password: 0, email: 0 } }
                ],
                as: "members"
            }
        }
    ] ).toArray();
    

    【讨论】:

    • 非常感谢,它有效!我不知道这意味着什么哈哈,但我会调查一下:D
    猜你喜欢
    • 2015-03-29
    • 1970-01-01
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-04
    相关资源
    最近更新 更多