【发布时间】:2023-03-08 17:58:01
【问题描述】:
我有以下结构的文档:
{
_id: "UNIQUE_ID",
myarray: [
{
mykey: '12345',
// other fields
},
{
// other fields
nestedarray: [
{
mykey: '67890',
// other fields
}
]
}
]
}
我需要从myarray 返回所有项目,其中mykey(在myarray 或nestedarray 的项目上)属于一组值。例如,对于上面的文档,如果值集是['12345, '67890'],则应该返回来自myarray 的两项。
我正在使用以下代码来做到这一点:
collection.aggregate([
{
$match: {
"_id": documentId,
$or: [
{ "myarray": {$elemMatch: {"mykey": { $in: ['12345, '67890'] } } } },
{ "myarray.$.nestedarray": {$elemMatch: {"mykey": { $in: ['12345, '67890'] } }} }
]
}
},
{
$project: {
myarray: {
$filter: {
input: '$myarray',
as: 'arrayitem',
cond: {
$or: [
{ $eq: ["$$arrayitem.mykey", '12345'] },
{ $eq: ["$$arrayitem.nestedarray.[$].mykey", '12345'] }
]
}
}
}
}
}
]);
但这只会返回 mykey 在 myarray 级别匹配的项目(在 nestedarray 内不匹配)。
我做错了什么?
另外,如何在 $filter 函数中使用 set ['12345, '67890'] 而不是单个值 '12345'?
澄清:
- 如果
mykey匹配来自myarray的项目:包括该项目(该项目将没有nestedarray字段) - 如果
mykey匹配来自nestedarray的项目:包括来自myarray的项目,其中包含nestedarray(也包含nestedarray的完整内容)。来自myarray的此项将没有mykey字段
示例:
数据:
{
_id: "UNIQUE_ID",
myarray: [
{
mykey: '11111',
// other fields
},
{
// other fields
nestedarray: [
{
mykey: '22222',
// other fields
},
{
mykey: '84325',
// other fields
}
]
},
{
mykey: '645644',
// other fields
},
{
// other fields
nestedarray: [
{
mykey: '23242',
// other fields
},
{
mykey: '23433',
// other fields
}
]
}
]
}
一组值:['11111', '22222']
预期的查询结果:
{
_id: "UNIQUE_ID",
myarray: [
{
mykey: '11111',
// other fields
},
{
// other fields
nestedarray: [
{
mykey: '22222',
// other fields
},
{
mykey: '84325',
// other fields
}
]
}
]
}
【问题讨论】:
-
如果
mykey存在于nestedarray中但不存在于myArray中怎么办? -
那么应该包含来自
myarray的包含nestedarray的项目,并且应该只包含来自nestedarray的匹配项目 -
好的,那么下面的答案对你有用。
-
@AnthonyWinzlet 实际上来自
nestedarray的所有项目都是必需的(即使其中只有一个匹配)。 -
所以基本上你不想过滤
nestedarray数组?
标签: mongodb aggregation-framework