将$ Redact与正则表达式结合使用

时间:2018-08-31 13:15:16

标签: mongodb aggregation-framework

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

假设我有此条目:

 {
   "_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'

2 个答案:

答案 0 :(得分:1)

您可以尝试以下汇总

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

答案 1 :(得分:0)

  

根据您在以下查询中的要求,该查询正在运行并且已经过正确测试

db.users.aggregate(

// Pipeline
[
    // Stage 1
    {
        $unwind: {
            path : "$logs",
            preserveNullAndEmptyArrays : true // optional
        }
    },

    // Stage 2
    {
        $group: {
                  _id: "$_id",
                  "title" :{$last:"$title"} , 
                      "creation_date" :{$last:"$creation_date"},
                  logs: {
                    $push: {
                      $cond: [ {$or:[{"$eq":[{ "$substr": [ "$logs.content", 0, 4 ] }, "Stop"]},{"$eq":[{ "$substr": [ "$logs.content", 0, 4 ] }, "stop"]}]},{"_id":"$logs._id","content":"$logs.content"},null]
                      }
                    }
                  }


    },

    // Stage 3
    {
        $project: {
            logs: {
                    $filter: {
                       input: "$logs",
                       as: "log",
                       cond: { $ne: [ "$$log", null ] }
                    }
                 }
        }
    },

]

// Created with Studio 3T, the IDE for MongoDB - https://studio3t.com/

);