我有以下收藏
{
"_id": "12345",
"Products": [
"Product1",
"Product2"
],
"State": "active",
}
并希望将其投影为类似于下面的输出
_id: "12345"
Products: "Product1, product2"
我尝试了这个,但我没有得到所需的命令分隔连接字符串的输出
{
_id: 1,
Products: {
$reduce: {
input: "$Products",
initialValue:"0" ,
in: {concat: ["$$value", "$$this"] }
}
}
}
您可以使用
$reduce
和 $concat
将值连接成一个字符串。需要使用 $cond
来确定值之间是否需要逗号。
db.collection.aggregate([
{
"$project": {
"_id": 1,
"Products": {
$reduce: {
input: "$Products",
initialValue: "",
in: {
$concat: [
"$$value",
{
$cond: [
{
$eq: [
"$$value",
""
]
},
"",
","
]
},
"$$this"
]
}
}
}
}
}
])