首页 > 解决方案 > 如何在深度嵌套的 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) 在这种情况下如何使用正则表达式?

标签: phpregexmongodb

解决方案


推荐阅读