gpt4 book ai didi

mongodb - 如何在 MongoDB 聚合方法中连接一个整数数组?

转载 作者:可可西里 更新时间:2023-11-01 10:38:00 25 4
gpt4 key购买 nike

我在 mongodb 文档中有一个字段,它是一个整数数组,如下所示:

import_ids=[5200, 4710, 100]

我想要这个数组作为双##分隔的字符串,所以预期的结果是

import_hashed="5200##4710##100"

我已经尝试在聚合方法的 $project 管道中使用以下代码。

 {
$projct:{
import_hashed:{
$reduce:{
input:"$import_ids",
initialValue:"",
in:{$concat:["$$value", "##", "$$this"]}
}
}
}
}

但是没有找到结果,也没有错误!

最佳答案

你可以试试下面的聚合

您可以使用 $toLower将整数转换为字符串或 $toString 的聚合如果您使用的是 mongodb 4.0

db.collection.aggregate([
{ "$project": {
"import_hashed": {
"$let": {
"vars": {
"key": {
"$reduce": {
"input": "$import_ids",
"initialValue": "",
"in": { "$concat": ["$$value", "##", { "$toLower": "$$this" }] }
}
}
},
"in": { "$substrCP": ["$$key", 2, { "$strLenCP": "$$key" }] }
}
}
}}
])

输出

{ "import_hashed": "5200##4710##100 }

关于mongodb - 如何在 MongoDB 聚合方法中连接一个整数数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52849656/

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