gpt4 book ai didi

mongodb - 使用 $nin 条件根据字段过滤数组中的元素

转载 作者:行者123 更新时间:2023-12-01 13:10:53 25 4
gpt4 key购买 nike

我有一个如下所示的 mongo 文档;

{
"_id": "123",
"name": "ABC",
"elements": {
"_id": "123",
"minorElements": [
[
{
"id": "xyz1",
"name": "xyz1"
}, {
"id": "xyz2",
"name": "xyz2"
}, {
"id": "xyz3",
"name": "xyz3"
}
],
[
{
"id": "xyz1",
"name": "xyz1"
}, {
"id": "xyz3",
"name": "xyz3"
}, {
"id": "xyz5",
"name": "xyz5"
}
]
]
}
}

“elements.minorElements”是一个数组数组。

如何编写 mongo 聚合以从“elements.minorElements”中删除“id”不在“xyz1”和“xyz2”中的对象?

预期输出:
{
"_id": "123",
"name": "ABC",
"elements": {
"_id": "123",
"minorElements": [
[{
"id": "xyz1",
"name": "xyz1"
}, {
"id": "xyz2",
"name": "xyz2"
}
],
[{
"id": "xyz1",
"name": "xyz1"
}
]
]
}
}

样本有效载荷 https://mongoplayground.net/p/9RjC6GzSQDQ

最佳答案

您需要 $map用于外部阵列和 $filter对于内部数组:

db.collection.aggregate([
{
$addFields: {
"elements.minorElements": {
$map: {
input: "$elements.minorElements",
as: "me",
in: {
$filter: {
input: "$$me",
cond: {
$in: [ "$$this.id", [ "xyz1", "xyz2" ] ]
}
}
}
}
}
}
}
])

Mongo Playground

关于mongodb - 使用 $nin 条件根据字段过滤数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60041715/

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