【问题标题】:MongoDB Aggregation - Exclude the record if the field is falseMongoDB 聚合 - 如果字段为 false,则排除记录
【发布时间】:2022-10-31 09:13:33
【问题描述】:

如果 active 字段是一个布尔值,我如何从聚合查询中排除整条记录是 false,好吗?

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

我已经尝试了上述的很多变体,但没有成功。任何帮助深表感谢!干杯,雷蒙德。

【问题讨论】:

  • 如果您可以共享示例输入数据和预期输出,那就太好了。而且我怀疑你错过了$filter 运算符的input 属性/参数。
  • 嗨永顺,根据文档,输入是一个解析为数组的表达式,这让我在这方面感到困惑,因为“活动”字段是一个布尔字段,我想从聚合中排除“活动”的记录=假

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

$filter 运算符不适合您的情况。因为它用于过滤数组字段中的文档。

相反,您需要一个$match 阶段并将其放置在第一阶段。

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

或相当于:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    相关资源
    最近更新 更多