【问题标题】:Use mongoDB $lookup to find documents in another collection not present inside an array使用 mongoDB $lookup 在数组中不存在的另一个集合中查找文档
【发布时间】:2021-04-15 15:43:03
【问题描述】:

我正在使用聚合框架来查询一个集合并创建一个活跃玩家数组(直到最后一个$lookup),之后我尝试使用$lookup$pipeline 来选择所有玩家来自activeUsers 数组中的另一个集合 (users)。

我目前的设置有什么办法吗?

Game.aggregate[{
  $match: {
    date: {
      $gte: ISODate('2021-04-10T00:00:00.355Z')
    },
    gameStatus: 'played'
  }
}, {
  $unwind: {
    path: '$players',
    preserveNullAndEmptyArrays: false
  }
}, {
  $group: {
    _id: '$players'
  }
}, {
  $group: {
    _id: null,
    activeUsers: {
      $push: '$_id'
    }
  }
}, {
  $project: {
    activeUsers: true,
    _id: false
  }
}, {
  $lookup: {
    from: 'users',
    'let': {
      active: '$activeUsers'
    },
    pipeline: [{
        $match: {
          deactivated: false,
          // The rest of the query works fine but here I would like to 
          // select only the elements that *aren't* inside
          // the array (instead of the ones that *are* inside)
          // but if I use '$nin' here mongoDB throws 
          // an 'unrecognized' error 
          $expr: {
            $in: [
              '$_id',
              '$$active'
            ]
          }
        }
      },
      {
        $project: {
          _id: 1
        }
      }
    ],
    as: 'users'
  }
}]

谢谢

【问题讨论】:

  • 就这样使用$not { $expr: { $not: { $in: ['$_id', '$$active'] } } }
  • 请将您的评论添加为答案,以便我将其选为已接受的答案。

标签: javascript node.js mongodb aggregation-framework lookup


【解决方案1】:

对于否定条件,在 $in 运算符之前使用 $not

{ $expr: { $not: { $in: ['$_id', '$$active'] } } }

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 2014-03-19
    • 2017-06-24
    相关资源
    最近更新 更多