如何将字符串数组映射和缩减为具有多个值的单个对象
How to Map and reduce an array of Strings to a single object with multiple values
我有一个文件看起来像这样:
{
_id: ObjectId("6222ca4252925ad4c3faec08"),
value: ["test1","test2"]
}
我想得到:
{
_id: ObjectId("6222ca4252925ad4c3faec08"),
“value”:
{
“value1”: "test1",
“value2”: "test2"
}
}
我曾尝试使用 reduce,但我得到了一个对象中的每个值,但非常接近。请让我知道我做错了什么:
代码:
{
"$project": {
"value": {
$reduce: {
input: "$value",
initialValue: [],
in: {$concatArrays: [
"$$value",
[{"name": "$$this"}]
]}
}
}
}
}
结果:
{
"_id" : ObjectId("6222ca4252925ad4c3faec08"),
"value" : [
{
"name" : "test1"
},
{
"name" : "test2"
}
]
}
目前您正在使用 $reduce
, Instead you can try using $map
to create an array of format [key, value]
and then use $arrayToObject
创建一个数组以将其转换为地图,如下所示:
[
{
"$project": {
"provider": {
"$arrayToObject": {
"$map": {
"input": "$value",
"as": "v",
"in": [
{
"$concat": [
"value",
{
"$toString": {
"$indexOfArray": [
"$value",
"$$v"
]
}
}
]
},
"$$v"
]
}
}
}
}
}
]
$indexOfArray
只是获取value(N)
格式的key。
我有一个文件看起来像这样:
{
_id: ObjectId("6222ca4252925ad4c3faec08"),
value: ["test1","test2"]
}
我想得到:
{
_id: ObjectId("6222ca4252925ad4c3faec08"),
“value”:
{
“value1”: "test1",
“value2”: "test2"
}
}
我曾尝试使用 reduce,但我得到了一个对象中的每个值,但非常接近。请让我知道我做错了什么:
代码:
{
"$project": {
"value": {
$reduce: {
input: "$value",
initialValue: [],
in: {$concatArrays: [
"$$value",
[{"name": "$$this"}]
]}
}
}
}
}
结果:
{
"_id" : ObjectId("6222ca4252925ad4c3faec08"),
"value" : [
{
"name" : "test1"
},
{
"name" : "test2"
}
]
}
目前您正在使用 $reduce
, Instead you can try using $map
to create an array of format [key, value]
and then use $arrayToObject
创建一个数组以将其转换为地图,如下所示:
[
{
"$project": {
"provider": {
"$arrayToObject": {
"$map": {
"input": "$value",
"as": "v",
"in": [
{
"$concat": [
"value",
{
"$toString": {
"$indexOfArray": [
"$value",
"$$v"
]
}
}
]
},
"$$v"
]
}
}
}
}
}
]
$indexOfArray
只是获取value(N)
格式的key。