首页 > 解决方案 > 将 $Redact 与正则表达式一起使用

问题描述

在聚合管道中,我试图根据该对象中字段的值过滤对象数组的某些元素。

假设我有这个条目:

 {
   "_id": "5b8911d346d19645f8a66bf4",
   "title": "test task",
   "creation_date": "2018-08-31T10:00:51.598Z",
   "logs": [
    {
       "_id": "5b89126c46d19645f8a66bfb",
       "content": "Running"
    },
    {
       "_id": "5b89128646d19645f8a66bfd",
       "content": "Stopping"
    },
    {
       "_id": "5b89128646d19645f8a66bfd",
       "content": "Stopped"
    }
   ]
 }

我的目标是仅过滤stop其内容中包含该单词的日志:

 {
   "_id": "5b8911d346d19645f8a66bf4",
   "title": "test task",
   "creation_date": "2018-08-31T10:00:51.598Z",
   "logs": [
    {
       "_id": "5b89128646d19645f8a66bfd",
       "content": "Stopping"
    },
    {
       "_id": "5b89128646d19645f8a66bfd",
       "content": "Stopped"
    }
   ]
 }

我尝试使用$redact消除所有不包含该stop单词的日志:

$redact: {
   $cond: {
      if: { $match: { "logs.content": { $regex: "stop", $options: 'i' }}},
      then: "$$KEEP",
      else: "$$PRUNE"
   }
}

但我不断收到错误:

Unrecognized expression '$match'

标签: mongodbaggregation-framework

解决方案


您可以尝试以下聚合

db.collection.aggregate([
  { "$addFields": {
    "logs": {
      "$filter": {
        "input": "$logs",
        "cond": {
          "$ne": [
            { "$indexOfBytes": [
              { "$toUpper": "$$this.content" },
              { "$toUpper": "stop" }
            ]},
            -1
          ]
        }
      }
    }
  }}
])

输出

[
  {
    "_id": "5b8911d346d19645f8a66bf4",
    "creation_date": "2018-08-31T10:00:51.598Z",
    "logs": [
      {
        "_id": "5b89128646d19645f8a66bfd",
        "content": "Stopping"
      },
      {
        "_id": "5b89128646d19645f8a66bfd",
        "content": "Stopped"
      }
    ],
    "title": "test task"
  }
]

推荐阅读