最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to convert array to string in mongodb - Stack Overflow

programmeradmin1浏览0评论

I have below schema

{
 id: 123,
 values:[
   {valueId: "12444", name: "asd"},
   {valueId: "555", name: "www"},
 ]
}

i want to convert it into (bine name into single string)

{
 id: 123,
 values: "asdwww"
}

i have tried below aggregate which puts all name value in an array

$project: {
      attributes: {
        "$map": {
          "input": "$attributes",
          "as": "attr",
          "in": {
            "id": "$$attr.id",
            "values": "$$attr.values.name"
          }
        }
      }
    },

which makes it into

{
 id: 123,
 values:[
     "asd",
     "www"
   ]
}

i want to have values as single string value as "asd,www" or "asdwww"

I have below schema

{
 id: 123,
 values:[
   {valueId: "12444", name: "asd"},
   {valueId: "555", name: "www"},
 ]
}

i want to convert it into (bine name into single string)

{
 id: 123,
 values: "asdwww"
}

i have tried below aggregate which puts all name value in an array

$project: {
      attributes: {
        "$map": {
          "input": "$attributes",
          "as": "attr",
          "in": {
            "id": "$$attr.id",
            "values": "$$attr.values.name"
          }
        }
      }
    },

which makes it into

{
 id: 123,
 values:[
     "asd",
     "www"
   ]
}

i want to have values as single string value as "asd,www" or "asdwww"

Share Improve this question edited Nov 3, 2020 at 9:20 mickl 50.1k9 gold badges70 silver badges98 bronze badges asked Nov 3, 2020 at 9:16 Akash SalunkheAkash Salunkhe 3144 silver badges14 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

You need $reduce instead of $map:

db.collection.aggregate([
    {
        $project: {
            _id: 1,
            values: {
                $reduce: {
                    input: "$values",
                    initialValue: "",
                    in: { $concat: [ "$$value", "$$this.name" ] }
                }
            }
        }
    }
])

Mongo Playground

Here's an example which shows how to handle delimiters

发布评论

评论列表(0)

  1. 暂无评论