gpt4 book ai didi

node.js - MongoDB 使用聚合根据条件从嵌套数组中删除对象

转载 作者:行者123 更新时间:2023-12-05 03:17:45 26 4
gpt4 key购买 nike

我有一个嵌套数组,我必须根据使用聚合的条件删除一个对象

这是我从 mongodb 得到的 JSON

{
"_id": "633d275ceb34a28755974032",
"name": "free",
"products": [
{
"title": "Product 1",
"phone": [
{
"title": "Best Phone 1 ",
"video": {
"Location": "https://video.mp4"
},
"freePreview": true
}
]
},
{
"title": "Product 2",
"phone": [
{
"title": "Best Phone 2",
"video": {
"Location": "https://video.mp4"
},
"freePreview": false
}
]
}

]
}

但是我需要这样的数据

{
"_id": "633d275ceb34a28755974032",
"name": "free",
"products": [
{
"title": "Product 1",
"phone": [
{
"title": "Best Phone 1 ",
"video": {
"Location": "https://video.mp4"
},
"freePreview": true
}
]
},
{
"title": "Product 2",
"phone": [
{
"title": "Best Phone 2",
"freePreview": false
}
]
}

]
}

由于 freePreview 为 false,此数据 “video object” 已从 phone 数组中移除,

Based upon the freePreview condition , help me to remove the video object

最佳答案

你需要使用双 $map运算符遍历数组数组并使用 $cond$$REMOVE 一起有条件地删除值:

db.collection.aggregate([
{
$addFields: {
products: {
$map: {
input: "$products",
as: "p",
in: {
title: "$$p.title",
phone: {
$map: {
input: "$$p.phone",
in: {
title: "$$this.title",
freePreview: "$$this.freePreview",
video: {
$cond: {
if: {
$eq: [
false,
"$$this.freePreview"
]
},
then: "$$REMOVE",
else: "$$this.video"
}
}
}
}
}
}
}
}
}
}
])

Mongo Playground

Here's一个类似的例子。

关于node.js - MongoDB 使用聚合根据条件从嵌套数组中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73974963/

26 4 0
文章推荐: typescript - 根据 typescript 函数中的另一个参数限制一个参数的类型
文章推荐: python - 如何使用 R reticulate 激活现有的 Python 环境
文章推荐: c# - 如何在 Expression 中转换可以是对象或 List 的 TResult?