MongoDB:聚合,将对象数组转换为字符串值

时间:2020-08-07 10:47:06

标签: javascript mongodb mongoose mongodb-query aggregation-framework

我的问题与MongoDB Aggregation join array of strings to single string非常相似,但是不是像['Batman', 'Robin']这样的纯数组,而是有对象数组:

_id: 1,
field_value: [
  {
    _id: 2,
    name: "Batman"
  },
  {
    _id: 3,
    name: "Robin"
  }
]

我正在尝试使用$reduce,但出现错误。

我想收到以下结果:

  _id: 1,
  field_value: "Batman, Robin" /** <= String value */

或至少一个属性值数组:

  _id: 1,
  field_value: ["Batman", "Robin"] /** <= Array of strings (name property) */

我的MongoPlayground data example

1 个答案:

答案 0 :(得分:1)

您需要使用与$reduce相同的方法,$$this代表单个field_value实体,因此您需要$$this.name

db.collection.aggregate([
    {
        $project: {
            field_value: {
                $reduce: {
                    input: "$field_value",
                    initialValue: "",
                    in: {
                        $concat: [
                            "$$value",
                            { $cond: [ { $eq: [ "$$value", "" ] }, "", "," ] },
                            { $toString: "$$this.name" }
                        ]
                    }
                }
            }
        }
    }
])

Mongo Playground