gpt4 book ai didi

mongodb - 如果它是一个数组,如何连接字符串数组字段以显示为一个字符串

转载 作者:行者123 更新时间:2023-12-05 04:56:37 24 4
gpt4 key购买 nike

以下是我收藏的两份文件:

{
"_id": {
"$oid": "5f48e358d43721376c397f54"
},
"heading": "this is heading",
"tags": ["tag1","tag2","tag3"],
"categories": ["projA", "projectA2"],
"content": ["This", "is", "the", "content", "of", "the", "document"],
"timestamp": 1598612312.506219,
"lang": "en"
}

{
"_id": {
"$oid": "5f48e358d43721376c397f53"
},
"heading": "this is heading",
"tags": "tag1,tag2,tag3",
"categories": "projA, projectA2",
"content": "This is the content of the document",
"timestamp": 1598612312.506219,
"lang": "en"
}

我想编写一个查询,连接第一个文档的 content 元素并按原样打印第二个(因为它不是数组)。

我正在使用以下脚本来连接,但它在第二个文档上给出了错误,说它需要是一个数组,但事实并非如此。我不知道如何在这种情况下使用 switch 语句或嵌套 if 条件:

    "$addFields": {
content: {
"$reduce": {
"input": "$content",
"initialValue": "",
"in": {
"$cond": {
"if": { "$eq": [ { "$indexOfArray": [ "$content", "$$this" ] }, 0 ] },
"then": { "$concat": [ "$$value", "$$this" ] },
"else": { "$concat": [ "$$value", "\n", "$$this" ] }
}
}
}
}
}

我是 mongo DB 的新手,所以我们将不胜感激。

最佳答案

你可以试试,

  • $cond 检查内容类型是否为数组,$reduce 连接内容字符串,$trim 删除空格<
db.collection.aggregate([
{
$addFields: {
content: {
$cond: [
{ $eq: [{ $type: "$content" }, "array"] },
{
$trim: {
input: {
$reduce: {
input: "$content",
initialValue: "",
in: { $concat: ["$$value", " ", "$$this"] }
}
}
}
},
"$content"
]
}
}
}
])

Playground

关于mongodb - 如果它是一个数组,如何连接字符串数组字段以显示为一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64820258/

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