【发布时间】:2023-03-07 09:33:01
【问题描述】:
我想获取所有缺少标签的项目(或更好的项目 ID)。
如果子项缺少其父项的标记,则应将其输出。
文件如下所示:
[
{
id: 1,
tags: [
"a",
"b"
],
childs: [
2,
3
]
},
{
id: 2,
tags: [
"a"
],
childs: []
},
{
id: 3,
tags: [],
childs: []
},
{
id: 4,
tags: [
"c"
],
childs: [
5
]
},
{
id: 5,
tags: [
"c"
],
childs: []
},
{
id: 6,
tags: [
"b"
],
childs: [
5
]
},
{
id: 7,
tags: [],
childs: []
},
]
现在我想按标签名称搜索以获取缺少标签的项目。
想要的结果应该是这样的:
检查标签“a”:
{
id: 3,
...
}
or
{
ids: [3]
}
检查标签“b”:
{
id: 2,
...
},
{
id: 3,
...
}
or
{
ids: [2, 3]
}
我尝试使用查找和管道功能进行聚合,但没有成功。
[{
$match: {
tags: "a",
childs: {
$ne: []
}
}
}, {
$lookup: {
from: 'collection1',
localField: 'childs',
foreignField: 'id',
as: 'childs_items',
pipeline: [{
$matching : {
"tags": {
$nin: "a"
}
}
}]
}
}]
最好的方法是什么?
编辑:将最后两个文档的文档示例标签更改为“c” EDIT2:添加示例数据
【问题讨论】:
-
感谢您的建议,但这不是我正在寻找的确切结果。我编辑了帖子以澄清问题。数据集有 n 个不同的标签,只有当父母有标签时,孩子也需要它。
标签: mongodb mongoose mongodb-query aggregation-framework