在MongoDB中过滤深度嵌套的数组



我需要用深度嵌套的数组数据过滤mongo集合。该文档有三个嵌套级别。以下是示例文档。要求是用";"状态";作为";"已验证";以及过滤器";array1";以及";array2";基于条件并且仅返回具有匹配数据的记录。

To summarise the filter params,
"status":"verified",
"name": "john",
"city": "mexico"
[
{
"_id": "111",
"array1": [
{
"name": "john",
"array2": [
{
"city": "mexico",
"array3": [
{
"address": "address1",
"status": "verified"
},
{
"address": "address2",
"status": "unverified"
}
]
}
]
}
]
},
{
"_id": "112",
"array1": [
{
"name": "john",
"array2": [
{
"city": "mexico",
"array3": [
{
"address": "address1",
"status": "unverified"
},
{
"address": "address2",
"status": "unverified"
}
]
}
]
}
]
}
]

预期输出如下,

{
"_id": "111",
"array1": [
{
"name": "john",
"array2": [
{
"city": "mexico",
"array3": [
{
"address": "address1",
"status": "verified"
}
]
}
]
}
]
}

以下是如何使用嵌套的$filter$map来实现这一点,因为您会看到,由于使用模式很复杂,语法不是很干净。

在不了解您的产品的情况下,我建议您重新访问它,根据您的常见访问模式进行重组可能是值得的。

db.collection.aggregate([
{
$match: {
"array1.array2.array3.status": "verified"
}
},
{
$addFields: {
array1: {
$filter: {
input: {
$map: {
input: "$array1",
as: "mapone",
in: {
"$mergeObjects": [
"$$mapone",
{
array2: {
$filter: {
input: {
$map: {
input: "$$mapone.array2",
as: "maptwo",
in: {
"$mergeObjects": [
"$$maptwo",
{
array3: {
$filter: {
input: "$$maptwo.array3",
as: "three",
cond: {
$eq: [
"$$three.status",
"verified"
]
}
}
}
}
]
}
}
},
as: "filtertwo",
cond: {
$and: [
{
$gt: [
{
$size: [
"$$filtertwo.array3"
]
},
0
]
},
{
$eq: [
"$$filtertwo.city",
"mexico"
]
}
]
}
}
}
}
]
}
}
},
as: "filterone",
cond: {
$and: [
{
$gt: [
{
$size: [
"$$filterone.array2"
]
},
0
]
},
{
$eq: [
"$$filterone.name",
"john"
]
}
]
}
}
}
}
}
])

Mongo游乐场

最新更新