'How to exclude results within the Mongo aggregation pipeline?

I'm new to the Mongo aggregation pipeline, and what I'm trying to do is find a simple way to exclude documents from my query. Each document in this collection can have multiple usernames. What I'm trying to exclude in my aggregation are any documents which have usernames other than userA and userB. What I'd like to do is something like:

...
{$dontmatch: {usernames: {$nin: ['userA', 'userB']}}}

My current query:

...
{$match:{
    $or: [
        {$and: [{usernames: {$size: 1}}, {usernames: {$in: ["userA", "userB"]}}]},
        {$and: [{usernames: {$size: 2}}, {usernames: {$all: ["userA", "userB"]}}]}
    ]}
}

What I have at the moment works, but I'm just wondering if there is a more clean or efficient way of doing this, such as I've suggested above?



Solution 1:[1]

Just came across this, if I understand the question correctly - we want to exclude the documents where the usernames array contains anything other than "userA" and "userB".

One possible way to achieve this using aggregation pipeline would be something like this: https://mongoplayground.net/p/oncv4_iRx35

Here's what I did:

  1. Use $project stage to create empty "usernames" array where the condition doesn't satisfy
  2. Use $addFields to add a size field containing the size of modified usernames array
  3. Use $match to filter out the desired documents.

There might be more succinct approaches to this but this is the one I came up with.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman