Home > Enterprise >  MongoDb $filter, then get distinct count
MongoDb $filter, then get distinct count

Time:11-22

I am working against a mongo collection that has the following schema

{ _id: "123", Items: [...] }

I current have a pipeline that goes through the collection and uses $faceting to do some aggregation on the content of Items.

Here is what that looks like:

"myFacet": [
    "$project": {
       "_id": 1,
       "Name": 1,
       "totalCount": {
           "$size": {
                "$filter": { ... }
           }
       }

    }
]

What I am trying to do is do the same thing as totalCount, but one step further and just get a distinct count of the results.

I am aware of how I would do this in a normal aggregation by $unwinding, then $matching, and then $group.

But, I'm a little lost if I can do any further operations on the array in $filter that would give me some sort of distinct count. Before I go and refactor the entire query, I'd like to see if there's a way to accomplish it first.

CodePudding user response:

You can do something like:

"myFacet": [
    {"$project": {
       "_id": 1,
       "Name": 1,
       "data": {"$filter": { ... }}
      }
   },
   {"$project": {
       "_id": 1,
       "Name": 1,
       "totalCount": {$size:'$data'},
       "distinctCount": {$size: {$setIntersection: '$data'}}
   }}
]
  • Related