gpt4 book ai didi

Mongodb - 从数组、匹配项属性或子数组项属性聚合项

转载 作者:可可西里 更新时间:2023-11-01 09:12:41 25 4
gpt4 key购买 nike

我有以下结构的文档:

{
_id: "UNIQUE_ID",
myarray: [
{
mykey: '12345',
// other fields
},
{
// other fields
nestedarray: [
{
mykey: '67890',
// other fields
}
]
}
]
}

我需要返回 myarraymykey 的所有项目(在 myarraynestedarray 的项目上) ) 属于一组值。例如,对于上面的文档,如果值集是 ['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'] }
]
}
}
}
}
}
]);

但这只会返回 mykeymyarray 级别匹配的项目(不在 nestedarray 内匹配)。

我做错了什么?

此外,我如何在 $filter 函数中使用集合 ['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
}
]
}
]
}

最佳答案

您可以使用单个 $filter然后作为 cond 您可以直接检查 mykey 或使用 $anyElementTrue对于一个数组。

db.col.aggregate([
{
$project: {
myarray: {
$filter: {
input: "$myarray",
cond: {
$or: [
{ $in: [ "$$this.mykey", ["11111", "22222"] ] },
{ $anyElementTrue: [
{
$map: {
input: { $ifNull: [ "$$this.nestedarray", [] ] },
as: "na",
in: { $in: [ "$$na.mykey", ["11111", "22222"] ] }
}
}
]
}
]
}
}
}
}
}
])

Mongo playground

关于Mongodb - 从数组、匹配项属性或子数组项属性聚合项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55598732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com