Home > Enterprise >  MongoDB Simple Aggregation Exclude Record if Field is False
MongoDB Simple Aggregation Exclude Record if Field is False

Time:05-01

How can I exclude a whole record from an aggregation query if the 'active' field, which is a boolean, is false, please?

user.aggregate([
        {
            '$search': {
                'index': 'search-index', 
                'text': {
                    'query': searchTerm, 
                    'path': 'name'
                }
            }
        }, {
            '$project': {
                'active': {
                    '$filter': {
                        'cond': {
                            '$ne': [
                                '$active', false
                            ]
                        }
                    }
                }, 
                'createdAt': 1, 
                'email': 1, 
                'id': 1, 
                'avatar': 1, 
                'name': 1, 
                'username': 1, 
            }
        }, {
            '$sort': {
                'createdAt': -1
            }
        }, {
            '$skip': skip
        }, {
            '$limit': limit
        }
    ])

I have tried a lot of variations of the above, with no success. Any help very much appreciated! Cheers, Raymond

CodePudding user response:

$filter operator isn't suitable in your case. As it is used to filter the documents in an array field.

Instead, you need a $match stage and place it in the first stage.

user.aggregate([
  { 
    $match: { 
      $expr: { 
        $ne: [
          "$active", 
          false
        ] 
      } 
    } 
  },
  ...  // Following stages
])

Or equivalent to:

user.aggregate([
  { 
    $match: { 
      active: true 
    } 
  },
  ...  // Following stages
])
  • Related