aja228
aja228

Reputation: 68

Concat Arrays on all fields MongoDB

Imagine I have this collection:

{
  id: 1,
  b: { 
   "field1": ['foo'],
   "field2": ['bar']
  }
}
{
  id: 2,
  b: { 
   "field2": ["foobar"],
   "field3": ["foofoo"]
  }
}

And I want to obtain a new collection with MongoDB:

{
 id: 1,
 b_grouped: ['foo', 'bar']
}
{
 id: 2,
 b_grouped: ["foobar", "foofoo"]
}

I don't know all the name of the fields in the documents, anyone would have an idea of how to perform something like this:

db.collection.aggregate(
   [
      { "$project": { "b_grouped": { $concatArrays: ["$b.*"] } } }
   ]
)

Upvotes: 5

Views: 427

Answers (1)

turivishal
turivishal

Reputation: 36104

You can try,

  • $reduce input b as a array after converting from object to array using $objectToArray, this will convert object in "k" (key), "v" (value) format array of object,
  • $concatArrays to concat initialValue ($$value) of $raduce and array of b object's field $$this.v
db.collection.aggregate([
  {
    $project: {
      b_grouped: {
        $reduce: {
          input: { $objectToArray: "$b" },
          initialValue: [],
          in: {
            $concatArrays: ["$$this.v", "$$value"]
          }
        }
      }
    }
  }
])

Playground

Upvotes: 10

Related Questions