0

Let's say I have an Array of Objects chars: [{'name':'tom','age':2},{'name':'jerry','age':3}]

What's the aggregation to get chars: ['tom','jerry'] or chars: 'tom,jerry' ?

I know I can get chars: [{'name':'tom'},{'name':'jerry'}] by $project on chars.name, but I want a more compact way to see what I have in the values since the keys are uninteresting.

1 Answer 1

1

You can use $reduce with $concatArrays for this:

db.collection.aggregate([
  {
    $project: {
      chars: {
        $reduce: {
          input: "$chars",
          initialValue: [],
          in: {
            $concatArrays: [
              "$$value",
              [
                "$$this.name"
              ]
            ]
          }
        }
      },
      _id: 0
    }
  }
])

Playground example

The $reduce is iterating array elements and create one result from them.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.