MongoDB数组作为字符串
我有一个文档集合,其中有两个数组作为项目, 我想将它们导出到CSV中,但数组显然是这样返回的 “项目”:[“一”、“二”、“三”] 电子表格将这些视为单独的一、二、三 有没有一种方法可以像数组一样进行转换MongoDB数组作为字符串,mongodb,type-conversion,Mongodb,Type Conversion,我有一个文档集合,其中有两个数组作为项目, 我想将它们导出到CSV中,但数组显然是这样返回的 “项目”:[“一”、“二”、“三”] 电子表格将这些视为单独的一、二、三 有没有一种方法可以像数组一样进行转换 ["one","two",'three"] 像这样的线 "one,two,three" 我更愿意在聚合查询中这样做,但是如果我需要转储到临时集合并转换集合,我可以这样做 感谢您的任何帮助您必须使用。 这将表达式应用于数组
["one","two",'three"]
像这样的线
"one,two,three"
我更愿意在聚合查询中这样做,但是如果我需要转储到临时集合并转换集合,我可以这样做
感谢您的任何帮助您必须使用。这将表达式应用于数组中的每个元素,并将它们组合为单个值 测试数据:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"key": [
"one",
"two",
"three"
]
}
]
db.collection.aggregate([
{
"$project": {
"key": {
"$rtrim": {
"input": {
"$reduce": {
"input": "$key",
"initialValue": "",
"in": {
"$concat": [
"$$value",
"$$this",
","
]
}
}
},
"chars": ","
}
}
}
}
])
[
{
"_id": ObjectId("5a934e000102030405000000"),
"key": "one,two,three"
}
]
查询:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"key": [
"one",
"two",
"three"
]
}
]
db.collection.aggregate([
{
"$project": {
"key": {
"$rtrim": {
"input": {
"$reduce": {
"input": "$key",
"initialValue": "",
"in": {
"$concat": [
"$$value",
"$$this",
","
]
}
}
},
"chars": ","
}
}
}
}
])
[
{
"_id": ObjectId("5a934e000102030405000000"),
"key": "one,two,three"
}
]
结果:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"key": [
"one",
"two",
"three"
]
}
]
db.collection.aggregate([
{
"$project": {
"key": {
"$rtrim": {
"input": {
"$reduce": {
"input": "$key",
"initialValue": "",
"in": {
"$concat": [
"$$value",
"$$this",
","
]
}
}
},
"chars": ","
}
}
}
}
])
[
{
"_id": ObjectId("5a934e000102030405000000"),
"key": "one,two,three"
}
]
用于消除最后一个,
剩余部分。如果没有此项,结果将是“一、二、三”
您可以在这里自己测试:这是否回答了您的问题:?