Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.*"] } } }
   ]
)
like image 597
aja228 Avatar asked Oct 23 '20 11:10

aja228


People also ask

What is $concatarrays operator in MongoDB?

MongoDB provides different types of array expression operators that are used in the aggregation pipeline stages and $concatArrays operator is one of them. This operator is used to concatenate two or more arrays and return a concatenated array.

How do I concatenate the item field and the description field?

The following operation uses the $concat operator to concatenate the item field and the description field with a " - " delimiter. { $project: { itemDescription: { $concat: [ "$item", " - ", "$description" ] } } }

What are the arguments to concatenate in $concatenate?

Concatenates strings and returns the concatenated string. { $concat: [ < expression1 >, < expression2 >, ... ] } The arguments can be any valid expression as long as they resolve to strings. For more information on expressions, see Expressions. If the argument resolves to a value of null or refers to a field that is missing, $concat returns null.

How to concatenate string fields in TIBCO JasperReports?

has usages on how to perform a concatenation of string fields. You can use the $concat operator within the aggregate operator. Example for TIBCO JasperReports Server version 7.5:


1 Answers

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

like image 85
turivishal Avatar answered Sep 27 '22 19:09

turivishal