Mongodb 将$Redact与正则表达式一起使用
在聚合管道中,我尝试根据对象中字段的值筛选对象数组的某些元素 假设我有这个条目:Mongodb 将$Redact与正则表达式一起使用,mongodb,aggregation-framework,Mongodb,Aggregation Framework,在聚合管道中,我尝试根据对象中字段的值筛选对象数组的某些元素 假设我有这个条目: { "_id": "5b8911d346d19645f8a66bf4", "title": "test task", "creation_date": "2018-08-31T10:00:51.598Z", "logs": [ { "_id": "5b89126c46d19645f8a66bfb", "content": "Running" },
{
"_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'
根据您的要求,下面的查询正在运行,并且经过了适当的测试
db.users.aggregate(
)) 您可以在下面尝试
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"
}
]
$regex
在4.1版本之前,聚合表达式中的支持将不可用。你可以看看这个。你可以使用提供的答案。可能是对答案的欺骗。我认为这个解决方案有一个问题:如果阶段2没有返回任何结果怎么办?在这种情况下,聚合将不返回父文档,而返回'stop'关键字,并且所有值都是为了示例而给出的。content
字段可以包含任何值,搜索值可以是除“stop”之外的任何其他值。我相信长度为4
的substr
不能应用于过滤器的任何情况检查我更新的查询我认为它适用于所有情况
[
{
"_id": "5b8911d346d19645f8a66bf4",
"creation_date": "2018-08-31T10:00:51.598Z",
"logs": [
{
"_id": "5b89128646d19645f8a66bfd",
"content": "Stopping"
},
{
"_id": "5b89128646d19645f8a66bfd",
"content": "Stopped"
}
],
"title": "test task"
}
]