我是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查询来对文档中的人员数组执行 regex操作,以便获得以下 answer
{
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'}
}
)
但这似乎不起作用。我想严格使用 regex 来处理我的案件。我试图对位置字段做同样的事情。
第二次尝试: 我还尝试执行与上述相同的操作,并向聚合管道添加另一个对Person Array的展开,如下所示。
db.collection.aggregate(
{'$unwind': '$components'},
{'$match' :
'_id': ObjectId("A"),
'components.index':'21',
'components.first':{'$regex':'^ja'}
},
{'$unwind': '$components.person'},
)
但这并没有改变任何东西。
我的问题:
1)可以这样做吗?
2)是否有使用查找查询的解决方案?
3)如果要展开 person数组,该怎么做?(展开深度嵌套的数组)
4)在这种情况下如何使用Regex?