1

My question is pretty similar to: MongoDB Aggregation join array of strings to single string, but instead of pure Array, like: ['Batman', 'Robin'] I have Array of objects:

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

I am trying to use $reduce but got error instead.

I want to receive the following result:

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

or at least array of property values:

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

My MongoPlayground data example

AlexZeDim
  • 3,520
  • 2
  • 28
  • 64
  • 1
    Does this answer your question: https://stackoverflow.com/questions/62346889/mongodb-how-to-flatten-some-query-results/62347449#62347449 ? – mickl Aug 07 '20 at 10:48

1 Answers1

3

You need the same approach with $reduce, $$this represents a single field_value entity so you need $$this.name:

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

Mongo Playground

mickl
  • 48,568
  • 9
  • 60
  • 89
  • 1
    Yes, this exactly what I need it too. I also updated my question with MongoPlayground example data. So the real question is: I can accept is as an answer to the question (*and I will do it, by default*), or should I delete the whole question, because it's a duplicate? – AlexZeDim Aug 07 '20 at 11:00
  • 1
    You can accept since you were asking about an array of objects – mickl Aug 07 '20 at 11:02