首页 > 解决方案 > 将 $lookup 与条件连接一起使用

问题描述

只要我有以下文件

用户

{
    uuid: string,
    isActive: boolean,
    lastLogin: datetime,
    createdOn: datetime
}

项目

{
    id: string,
    users: [
        {
            uuid: string,
            otherInfo: ...
        },
        {... more users}
    ]
}

我想选择自 2 周以来未登录且处于非活动状态或自 5 周以来没有项目的所有用户。

现在,2 周工作正常,但我似乎无法弄清楚如何做“5 周并且没有项目”部分

我想出了类似下面的东西,但最后一部分不起作用,因为$exists显然不是顶级操作员。

有人做过这样的事吗?谢谢!

return await this.collection
    .aggregate([
        {
            $match: {
                $and: [
                    {
                        $expr: {
                            $allElementsTrue: {
                                $map: {
                                    input: [`$lastLogin`, `$createdOn`],
                                    in: { $lt: [`$$this`, twoWeeksAgo] }
                                }
                            }
                        }
                    },
                    {
                        $or: [
                            {
                                isActive: false
                            },
                            {
                                $and: [
                                    {
                                        $expr: {
                                            $allElementsTrue: {
                                                $map: {
                                                    input: [`$lastLogin`, `$createdOn`],
                                                    in: { $lt: [`$$this`, fiveWeeksAgo] }
                                                }
                                            }
                                        }
                                    },
                                    {
                                        //No projects exists on this user
                                        $exists: {
                                            $lookup: {
                                                from: _.get(Config, `env.collection.projects`),
                                                let: {
                                                    currentUser: `$$ROOT`
                                                },
                                                pipeline: [
                                                    {
                                                        $project: {
                                                            _id: 0,
                                                            users: {
                                                                $filter: {
                                                                    input: `$users`,
                                                                    as: `user`,
                                                                    cond: {
                                                                        $eq: [`$$user.uuid`, `$currentUser.uuid`]
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                ]
                                            }
                                        }
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        }
    ])
    .toArray();

标签: node.jsmongodbaggregation-framework

解决方案


不确定为什么您认为$expr最初需要$match,但实际上:

const getResults = () => {

  const now = Date.now();
  const twoWeeksAgo = new Date(now - (1000 * 60 * 60 * 24 * 7 * 2 ));
  const fiveWeeksAgo = new Date(now - (1000 * 60 * 60 * 24 * 7 * 5 ));

  // as long a mongoDriverCollectionReference points to a "Collection" object
  // for the "users" collection

  return mongoDriverCollectionReference.aggregate([   
    // No $expr, since you can actually use an index. $expr cannot do that
    { "$match": {
      "$or": [
        // Active and "logged in"/created in the last 2 weeks
        { 
          "isActive": true,
          "$or": [
            { "lastLogin": { "$gte": twoWeeksAgo } },
            { "createdOn": { "$gte": twoWeeksAgo } }
          ]
        },
        // Also want those who...
        // Not Active and "logged in"/created in the last 5 weeks
        // we'll "tag" them later
        { 
          "isActive": false,
          "$or": [
            { "lastLogin": { "$gte": fiveWeeksAgo } },
            { "createdOn": { "$gte": fiveWeeksAgo } }
          ]
        }
      ]
    }},

    // Now we do the "conditional" stuff, just to return a matching result or not

    { "$lookup": {
      "from":  _.get(Config, `env.collection.projects`), // there are a lot cleaner ways to register models than this
      "let": {
        "uuid": {
          "$cond": {
            "if": "$isActive",   // this is boolean afterall
            "then": null,       // don't really want to match
            "else": "$uuid"     // Okay to match the 5 week results
          }
        }
      },
      "pipeline": [
        // Nothing complex here as null will return nothing. Just do $in for the array
        { "$match": {  "$in": [ "$$uuid", "$users.uuid" ] } },

        // Don't really need the detail, so just reduce any matches to one result of [null]
        { "$group": { "_id": null } }
      ],
      "as": "projects"
    }},

    // Now test if the $lookup returned something where it mattered
    { "$match": {
      "$or": [
        { "active": true },                   // remember we selected the active ones already
        {
          "projects.0": { "$exists": false }  // So now we only need to know the "inactive" returned no array result.
        }
      ]
    }}
  ]).toArray();   // returns a Promise
};

这非常简单,因为通过计算的表达式$expr实际上非常糟糕,而不是您在第一个管道阶段想要的。也“不是你需要的”,因为createdOn并且lastLogin真的不应该被合并到一个数组中,$allElementsTrue它只是一个AND条件,你描述的逻辑实际上意味着OR。所以$or这里做得很好。

$or的分离条件isActive也是如此true/false。同样“两周”“五周”。这当然不需要,$expr因为标准不等式范围匹配工作正常,并且使用“索引”。

那么你真的只想在 for 中做“有条件的”事情,而不是“它是否存在”的想法。您真正需要知道的(因为日期的范围选择实际上已经完成)是现在还是。它在哪里(根据您的逻辑意思是您不关心项目)只需将管道阶段中的used设为一个值,这样它就不会匹配并返回一个空数组。在哪里(也已经与之前的日期条件匹配)然后您使用实际值和“加入”(当然有项目的地方)。let$lookupactivetruefalseactive$$uuid$matchnull$lookupfalse

active然后,只需保留用户,然后只测试剩余的falseactive以查看"projects"数组是否$lookup实际返回任何内容,这只是一个简单的问题。如果没有,那么他们就没有项目。

这里可能应该注意的是,由于集合中users是一个“数组” ,因此您使用针对数组的单个值的条件。projects$in$match

请注意,为简洁起见,我们可以$group在内部管道中使用只返回一个结果,而不是可能与实际匹配的项目匹配很多。您不关心内容或“计数”,而只关心一个被退回或什么都没有。再次遵循提出的逻辑。

这可以获得您想要的结果,并且它以一种有效的方式实现,并且在可用的情况下实际使用索引。

当然也return await不会像你认为的那样做,事实上它是一个 ESLint 警告消息(我建议你在你的项目中启用 ESLint),因为这不是一件聪明的事情。它实际上什么也没做,因为无论如何您都需要await getResults()(根据示例命名),因为await关键字不是“魔术”,而只是一种更漂亮的写作方式then()。除了希望更容易理解之外,一旦你理解了async/await语法上的真正含义。


推荐阅读