简体   繁体   中英

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.

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,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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