php - 如何在深度嵌套的 MongoDB 文档中的数组上使用正则表达式?
问题描述
我是 MongoDB 的初学者,我希望我的以下问题对所有人都很清楚。
考虑以下文件-
{
'_id': ObjectId("A"),
components:[
0: {
index: 21,
abc:22,
person: [
{id:23, first:'Jack',last:'Sparrow', location:'USA,New York'},
{id:24, first:'Jack',last:'Ryan', location:'USA,New Jersey'},
{id:25, first:'Jill',last:'Ryan', location:'USA,New Jersey'},
{...}
]
},
1: {
index: 22,
abc:23,
person: [
{id:12, first:'Andy',last:'Sparrow', location:'USA,New York'},
{id:14, first:'Kate',last:'Ryan', location:'USA,New Jersey'},
{...}
]
},
]
}
现在我正在尝试编写一个 MongoDB 查询来对文档中的 person 数组执行正则表达式操作,以便得到以下答案
{
person:[
{id:23, first:'Jack',last:'Sparrow', location:'USA,New York'},
{id:24, first:'Jack',last:'Ryan', location:'USA,New Jersey'}
]
}
OR
{
components:[
person:[
{id:23, first:'Jack',last:'Sparrow', location:'USA,New York'},
{id:24, first:'Jack',last:'Ryan', location:'USA,New Jersey'}
]
]
}
我认为由于它是一个深度嵌套的查询,因此最好使用聚合。
第一次尝试:
db.collection.aggregate(
{'$unwind': '$components'},
{'$match' :
'_id': ObjectId("A"),
'components.index':'21',
'components.first':{'$regex':'^ja'}
}
)
但这似乎不起作用。我想严格使用正则表达式来让我的案例工作。我尝试对location 字段做同样的事情。
第二次尝试:我也尝试做与上面相同的事情,并在聚合管道中添加另一个用于 Person Array 的展开,如下所示。
db.collection.aggregate(
{'$unwind': '$components'},
{'$match' :
'_id': ObjectId("A"),
'components.index':'21',
'components.first':{'$regex':'^ja'}
},
{'$unwind': '$components.person'},
)
但这并没有改变什么。
我的问题:
1)有可能做到这一点吗?
2)有没有使用查找查询的解决方案?
3)如果我想展开人员数组,怎么做?(展开深度嵌套数组)
4) 在这种情况下如何使用正则表达式?
解决方案
推荐阅读
- django - 字段 'card_exp_month' 需要一个数字,但得到 (4,) - 添加到模型时的 Django 和条带 API
- node.js - MERN mongoDB 集合未更新且未发送响应
- android - 添加一个新的 CheckBox 和一个 editText 视图,当用户在 android 的键盘上点击 Done 时?
- jquery - 我的 AJAX 调用工作正常,但成功功能不起作用
- django - Django - PUT 端点验证器错误“wrapped_view() 缺少 1 个必需的位置参数:'request'”
- php - 尝试使用 PHP 脚本将值从 HTML 表单发送到电子邮件,使用代码时收到错误 405
- laravel - 如何修改关系?
- java - 使用 Blogger API 添加帖子不起作用
- terraform - Terraform - 向 ignore_changes 添加例外
- java - 为什么下面代码中java中的浮点默认值不是0.0f