gpt4 book ai didi

javascript - 如何将字符串转换为 int MongoDB 数组

转载 作者:行者123 更新时间:2023-12-03 08:32:18 24 4
gpt4 key购买 nike

在我的项目中,我有一个 excel 文件,该文件被转换为 mongodb 结构数据。

这是一个示例行:

appartamento:{
nome: 'Appartamento',
via: 'Via Roma 120',
ids_stile: '2, 3 11',
ids_personaggi: '8, 9, 21'
}

其中“ids_stile”和“ids_personaggi”是字符串。

是否可以将整数集合中的 ids_stile 和 ids_personaggi 转换为具有这样的结构?

appartamento:{
nome: 'Appartamento',
via: 'Via Roma 120',
ids_stile: [2, 3, 11],
ids_personaggi: [8, 9, 21]
}

谢谢

最佳答案

如果您想使用 mongo 来执行此操作,请尝试以下查询:

db.collection.aggregate([
{
"$match": {
"id": 0
}
},
{
"$set": {
"appartamento.ids_stile": {
"$split": [
"$appartamento.ids_stile",
","
]
},
"appartamento.ids_personaggi": {
"$split": [
"$appartamento.ids_personaggi",
","
]
}
}
},
{
"$project": {
"appartamento.ids_stile": {
"$map": {
"input": "$appartamento.ids_stile",
"as": "newArray",
"in": {
"$convert": {
"input": "$$newArray",
"to": "int",

}
}
}
},
"appartamento.ids_personaggi": {
"$map": {
"input": "$appartamento.ids_personaggi",
"as": "newArray",
"in": {
"$convert": {
"input": "$$newArray",
"to": "int",

}
}
}
},
"appartamento.nome": 1,
"appartamento.via": 1
}
}
])

基本上就是获取您想要的文档(我使用了 appartamento.nome 但您可以通过 _id 或任何您想要的内容进行匹配)。
然后,使用 $set$split 修改字段,创建一个以 ',' 分隔的字符串数组。
之后,项目字段使用 $map 使用新数组覆盖这两个字段,其中字符串数组中的每个值现在都转换为 int

示例 here

编辑:

要对许多文档执行此操作,只需删除 $match 阶段。

示例 here

关于javascript - 如何将字符串转换为 int MongoDB 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64767861/

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