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.*"] } } }
]
)
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.
The following operation uses the $concat operator to concatenate the item field and the description field with a " - " delimiter. { $project: { itemDescription: { $concat: [ "$item", " - ", "$description" ] } } }
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.
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:
You can try,
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,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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With