Ray Purchase
Ray Purchase

Reputation: 762

MongoDB Aggregation - Exclude the record if the field is false

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 is much appreciated! Cheers, Raymond.

Upvotes: 0

Views: 673

Answers (1)

Yong Shun
Yong Shun

Reputation: 51475

$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
])

Upvotes: 1

Related Questions