Reputation: 68
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
Reputation: 36104
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.vdb.collection.aggregate([
{
$project: {
b_grouped: {
$reduce: {
input: { $objectToArray: "$b" },
initialValue: [],
in: {
$concatArrays: ["$$this.v", "$$value"]
}
}
}
}
}
])
Upvotes: 10