简体   繁体   English

使用 mongoDB $lookup 在数组中不存在的另一个集合中查找文档

[英]Use mongoDB $lookup to find documents in another collection not present inside an array

I'm using the aggregate framework to query a collection and create an array of active players (up until the last $lookup ) after which I'm trying to use $lookup and $pipeline to select all the players from another collection ( users ) that are not present inside the activeUsers array.我正在使用聚合框架来查询一个集合并创建一个活跃玩家数组(直到最后一个$lookup ),之后我尝试使用$lookup$pipeline到 select 来自另一个集合的所有玩家( users存在于activeUsers数组中。

Is there any way of doing this with my current setup?我目前的设置有什么办法吗?

 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' } }]

Thanks谢谢

For negative condition use $not before $in operator,对于否定条件,在$in运算符之前使用$not

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM