Aggregation, using $filter at the root level

Is it possible to filter out documents on the root level?

Update: It is not visible in this example, but the reason why I don’t perform this deeper filtering inside the $match stage is because the field that is necessary for performing this filtering needs to be $lookup 'ed first

Example:

  1. A Match stage is run to retrieve all the documents that have a category value A1:
[
  {
    "category": "A1",
    "name": "Document1",
    "include": false
  },
  {
    "category": "A1",
    "name": "Document2",
    "include": true
  },
  {
    "category": "A1",
    "name": "Document4",
    "include": true
  },
  {
    "category": "A1",
    "name": "Document5",
    "include": false
}
],
  1. Now, how to filter out all the returned documents that have include set to false?

Thank you

Doing the following

is almost exactly the same as

So it is really not clear why just adding include:{$ne:false} or $not:{include:false} to your $match does not work?

The issue is that I would like to use $filter after $match. This need comes in scenarios as follows:

  1. An initial $match is done to retrieve the documents in their original shape.
  2. A $lookup is performed to populate specific fields on those found documents.
  3. Based on the $lookup results some originally retrieved documents need to be filtered out.

The use-case is still not clear. Based on the sample documents you provided

should work.

To understand better we will need documents from both collections. The current pipeline you have is also useful to see.

In your title you wrote at the root level but in your last post you mentioned $lookup which kind of imply documents within an array.