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

1

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

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?
You can accept since you were asking about an array of objects

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.